【问题标题】:Center a div in a section在一个部分中居中一个 div
【发布时间】:2013-05-07 20:32:43
【问题描述】:

我正在尝试将<div> 置于<section> 的中心。将 margin-left 和 margin-right 设置为 auto 不起作用(我常用的方法)。我忘记了什么?

jsFiddle的问题:http://jsfiddle.net/veWKh/

【问题讨论】:

标签: css margin centering


【解决方案1】:

设置宽度,否则div为显示块,宽度为100%:fiddle:http://jsfiddle.net/veWKh/1/

CSS:

section {
    background-color: rgba(0,0,0,0.2);
}

div {
    margin-left: auto;
    margin-right: auto;
    width: 100px;
}

【讨论】:

  • 显示内联块,而不是你需要一个文本对齐:中心。因为它是作为内联处理的。
【解决方案2】:

要使margin:auto 工作,您需要给div 一组width 例如:

div {
    width:100px;
    margin: 0 auto;
}

【讨论】:

    【解决方案3】:

    先设置宽度,否则会占满空间,设置边距无效

    div {
        width:30em; 
        margin-left: auto;
        margin-right: auto;
    }
    

    【讨论】:

      【解决方案4】:

      你的 div 的这个宽度没有限制,所以你在做什么是不可见的。

      div {
          display:block;
          width:50%;
          background-color: #ffffff;
          margin: 0 auto;
      }
      

      【讨论】:

        【解决方案5】:

        这很好用:

        section
        {
            text-align: center;
        }
        

        不过,这将使所有内容居中。否则你可以这样做:

        div 
        {
            display:block;
            text-align:center;
            margin: auto;
        }
        

        【讨论】:

          【解决方案6】:

          试试看

          section {
              background-color: rgba(0,0,0,0.2);
          }
          
          div {
              margin-left: auto;
              margin-right: auto;
              text-align: center;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2016-05-25
            • 1970-01-01
            • 2017-03-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多