padding:0 auto;不能使内容居中呢?


想设置一个div居中,使用padding:0 auto;width:1000px;
为什么不能是元素居中呢?
因为使用margin:0 auto;的话,居中的两边背景色会用空白·

web前端开发 htm css

荻野二秋目 8 years, 11 months ago

body 给个背景色

wazze answered 8 years, 11 months ago


 <div style="padding:0 auto">
        <p>This is a div!</p>
</div>

元素可以居中

所以LZ到底想实现什么效果

轻音女大学生 answered 8 years, 11 months ago

  1. padding 是不可以让内容居中的;
  2. margin: 0 auto; width: 1000px; 可以让div居中,必要条件就是 必须要规定盒子的宽度;
  3. 你也可以把要居中的div 设置成 display: inline-block; ,然后在父div加上 text-align: center; 也会让div居中;

示例:


 html


 
<style> .wrapper { text-align: center; } .wrapper >.center-div { display: inline-block; } </style> <div class="wrapper"> <div class="center-div"> 我是居中的 </div> </div>
TSUMI- answered 8 years, 11 months ago

具体原因不知道怎么说明,不过在w3.org上有一个说明: http://www.w3.org/TR/CSS21/visudet.html#blockwidth

If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

然后在 http://www.w3help.org/ 有一篇类似相关的文章,不知道是否能帮你 http://www.w3help.org/zh-cn/causes/RD8028

囧Smith answered 8 years, 11 months ago

Your Answer