Home  >  Article  >  Web Front-end  >  auto的使用_html/css_WEB-ITnose

auto的使用_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:50:231434browse

html

1 <div class="container">2     <div class="demo">  3     </div>4 </div>  

css

 1 .container{ 2       width:150px; 3       height:50px; 4       background:rgb(236,100,143); 5 } 6 .demo{ 7       background:rgb(141,163,210); 8       width:auto; 9       height:50px;10       margin-left:10px;11       margin-right:10px;12 }

1.margin-left与width为定值,margin-right:auto

此时写作auto状态的margin-right其实值为150-50-10=90px。

2.margin-left与margin-right为定值10px,width:auto

此时写作auto状态的width其实值为150-10-10=130px。

3.width为定值100px,margin-left和margin-right都是auto

此时.demo居中,写作auto状态的margin-left和margin-right值都为(150-100)/2=25px。

4.margin-left为定值10px,width和margin-right都是auto

此时设置为auto的外边距会减为0(margin-right:0),width值为150-10=140px。

5.margin-left,margin-right,width三者都设为auto

此时两个外边距都会设置为0,width值为150-0-0=150px。

说明

  1. 当margin-left,margin-right,width三者都设定值且总和大于父元素的宽度时(过分受限),margin-right将会被重置以符合宽度要求(针对从左往右读的语言,反之则重置margin-left)。
  2. padding和border都不能设置为auto,也绝不能为负数。
  3. 在正常流中margin-top或margin-bottom设置为auto会自动计算为0,无法做到垂直居中。
  4. margin:0 auto的水平居中效果不适用于内联元素(p,img),内联元素的水平居中可以用text-align:center,非要使用margin必须先display:block将其变为块状元素。

 

参考资料

《CSS权威指南》第7章 基本视觉格式化

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn