【问题标题】:how to align center to page of which child div has some fixed width如何将中心与具有固定宽度的子 div 的页面对齐
【发布时间】:2013-07-18 17:29:54
【问题描述】:

我有如下的html...

<div>
    <h1>centered text</h1>
    <p>some text</p>
</div>

还有 css....

div{display: table; text-align: center; width: 100%;}
p{width: 100px;}

在上面的代码中,h1 居中而不是 p。我尝试使用 margin-left: 50% to outer div 和 left: -50% to inner div 但显示额外的水平滚动条。所以,我想用另一种方法。

【问题讨论】:

    标签: html css


    【解决方案1】:

    更新p元素的样式:

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

    Demo here

    说明:

    h1 的文本居中是因为h1 元素从div 元素继承了text-align 属性,并且其宽度等于div 元素的宽度。

    您的p 元素也继承了中心文本对齐,但它只有 100px 长度并具有默认位置属性,因此 整个 p 元素粘贴在父元素的左侧div。您必须设置p 元素的左右边距以使整个p 元素div 内居中。

    【讨论】:

      【解决方案2】:

      你只需要这个:

      div{display: table; text-align: center; width: 100%; margin:0 auto}
      

      演示 http://jsfiddle.net/xfGh2/

      【讨论】:

      • 唯一的问题是他可能决定让图像或其他他不想居中的位。但如果他这样做了,那就去吧。 +1 了。
      【解决方案3】:

      p{width:100px;margin:0 auto;} 这将顶部和底部的边距设置为 0,但从左到右居中。

      Link to CodePen here

      【讨论】:

        【解决方案4】:

        使用

         margin-left:auto;  
         margin-right:auto;
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-05-26
          • 2014-09-20
          • 1970-01-01
          • 1970-01-01
          • 2012-06-13
          • 2019-05-27
          • 2011-03-08
          • 1970-01-01
          相关资源
          最近更新 更多