为什么给定宽元素设置左右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
同时为几项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
加入了left和right,可以用类似的方式达到水平居中。
高度计算
默认行为的高度计算则是一系列“撑高”规则,而非“适应于父级”规则。
常规流的非替换元素高度计算规则我之前已经引用过。
对于绝对定位元素,有以下算式:
top
margin-top
border-top-width
padding-top
height
padding-bottom
border-bottom-width
margin-bottom
bottom
因此margin-top: auto; margin-bottom:auto;
配合一系列设置,可以让绝对定位元素垂直居中:
http://jsfiddle.net/tvkkk62v/
当然这个方案有一些限制,优点和缺点我有一篇博文“整理:子容器垂直居中于父容器的方案”综合讲过,不再复述了。
为何这么设计,我有一个粗略的想法,待以后发展一下:
水平居中支持门槛低是因为大部分文本都是lr-tb顺序,网页设计倾向于从上往下溢出而非从左往右溢出。
哇哇哇是FakeFish。
= = 默认情况下 div的宽度可以自动撑满100%,height却没有。所以我假设dom中默认高度无限高,宽度100%
下方贴出对应的css样式表,根据个人理解,top和bottom都设置成0,靠近外部父容器边界,就会各抢一半,也就是我们说的居中,水平方向left和right也设置成0,效果也是一样的,相对于父元素居中。
- 为什么给定宽元素设置左右margin为…
- IE6下为元素的margin设置负值不起作用
- 为子元素设置margin-top会作用在父元素上?
- 为什么给行内块级元素inline-block添加margin-top为负值的时候不起作用?
- 子元素margin-top,为什么对父元素也起作用?
- 子元素设置margin-top,父元素也受影响
- 子元素设置margin-top,父元素也受影响
- 为什么margin-top不是作用于父元素
- 为什么「margin:auto」可以让块级元素水平居中?
- 为什么「margin:auto」可以让块级元素水平居中?
- css子元素设置margin时和父元素合并margin
- 左右margin加倍问题
- 在给定的数组中找出两个元素和为给定值的所有元素对
- 在给定的数组中找出两个元素和为给定值的所有元素对
- 为activity设置左右的切换动画
- CSS元素的width和水平margin的设置
- 设置margin-top值时,溢出到父元素
- css margin-top设置html元素之间的距离
- 通过上节的块设备驱动分析,本节便通过内存来模拟块设备驱动
- Mybatis3 执行insert语句后获…
- 微信小程序入门——小程序与页面的生命周期
- MySQL表名不区分大小写的设置方法
- Tomcat启动与关闭事件监听
- 为什么给定宽元素设置左右margin为…
- Sub-PU based Motion Vector Prediction
- Elasticsearch与Solr
- 对于Java应该明确这些知识点
- select在各个浏览器中的兼容性问题
- JavaScript设计模式--简单工厂模式
- ConcurrentMap.putIfAbsent(key,va…
- tomcat7中maxConnections、maxThre…
- ClassLoader工作机制