为什么给定宽元素设置左右margin为…

来源:互联网 发布:淘宝加入购物车没反应 编辑:程序博客网 时间:2024/04/27 22:37

原文地址(本页做了些修改):https://segmentfault.com/q/1010000000689833


为什么给定宽元素设置左右margin为auto就可以居中?垂直为什么不能这么干?

最简单的理由:因为宽度计算默认涉及包含块(可粗略理解为父级元素),而高度计算默认涉及内部元素。

要居中,必须相对父级计算,而非内部元素。


宽度计算

默认的宽度规则是“适应于父级”规则。(当然有一些计算模式会让元素适应于内部元素,超出话题范围,暂且不谈。)

W3 CSS 2.1第十章里为常规流替换和非替换块级元素定义了这个算式:

margin-left border-left-width padding-left width padding-right border-right-width margin-right = width of containingblock

同时为几项auto设置了额外的算法:

If there is exactlyone value specified as 'auto', its used value follows from theequality.
If 'width' is set to 'auto', any other 'auto' values become '0' and'width' follows from the resulting equality.
If both 'margin-left' and 'margin-right' are 'auto', their usedvalues are equal. This horizontally centers the element withrespect to the edges of the containing block.

这就是auto可以水平居中的原因。

对于绝对定位元素,有以下算式:

left margin-left border-left-width padding-left width padding-right border-right-width margin-right right = widthof containing block

加入了left和right,可以用类似的方式达到水平居中。

高度计算

默认行为的高度计算则是一系列“撑高”规则,而非“适应于父级”规则。

常规流的非替换元素高度计算规则我之前已经引用过。

对于绝对定位元素,有以下算式:

top margin-top border-top-width padding-top height padding-bottom border-bottom-width margin-bottom bottom =height of containing block

因此margin-top: auto; margin-bottom:auto;配合一系列设置,可以让绝对定位元素垂直居中:

http://jsfiddle.net/tvkkk62v/

当然这个方案有一些限制,优点和缺点我有一篇博文“整理:子容器垂直居中于父容器的方案”综合讲过,不再复述了。


为何这么设计,我有一个粗略的想法,待以后发展一下:

水平居中支持门槛低是因为大部分文本都是lr-tb顺序,网页设计倾向于从上往下溢出而非从左往右溢出。

 

哇哇哇是FakeFish。 我给个我脑子里的答案,不为答案负责啊!

= = 默认情况下 div的宽度可以自动撑满100%,height却没有。所以我假设dom中默认高度无限高,宽度100% 那么基于这么个假设的情况下。。。就好解释了。。。根本不知道高度多少怎么auto= =

 

下方贴出对应的css样式表,根据个人理解,top和bottom都设置成0,靠近外部父容器边界,就会各抢一半,也就是我们说的居中,水平方向left和right也设置成0,效果也是一样的,相对于父元素居中。

 

.outer{
   position: relative;//声明内部绝对定位的父容器
   background: #333;
   height: 100px;
   width: 100%;
}


.inner{
   position: absolute;//内部元素绝对定位
   margin-left: auto;
   margin-right: auto;
   margin-top: auto;
   margin-bottom: auto;
   left: 0;
   right: 0;
   top: 0;
   bottom: 0;
   width: 20px;//注意内部元素要加上宽度和高度
   height: 20px;
   background: #F5F5F5;
   

}
阅读全文
0 0
原创粉丝点击