javascript - 为何margin:auto auto 不能上下左右对齐?
问题描述
一个html中只有一个p。
<p class='test'></p>css1:.test{ width:200px; height:200px; border:1px solid red; margin:0 auto; }
css1可以使p.test左右居中。
css2:
.test{ width:200px; height:200px; border:1px solid red; margin:auto auto; } 为何css2不可以使p.test上下左右居中?? 请不要回答如何使他p.test上下左右居中,请回答为何margin:auto auto;不能上下左右居中??
问题解答
回答1:The following constraints must hold among the used values of the other properties:
’margin-left’ + ’border-left-width’ + ’padding-left’ + ’width’ + ’padding-right’ + ’border-right-width’ + ’margin-right’ = width of containing block
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.
下面是关于高度的:
If ’margin-top’, or ’margin-bottom’ are ’auto’, their used value is 0. If ’height’ is ’auto’, the height depends on whether the element has any block-level children and whether it has padding or borders:
因为规范就是这么规定的算法,浏览器就是这么实现的。
CSS规范
回答2:这是个好问题,那我问你,当一行存在两个元素的时候,你可以左右居中吗?同理当你的上下都可能有元素存在的情况下你要浏览器怎么去计算对应元素应该存在的位置?
回答3:不能吧,上下对齐如果不用flex布局,没啥太好的办法。virtical–align也不太好用!
回答4:不能,如果想上下左右对居中的话,推荐使用flex布局,其次是table,table-cell或者定位
相关文章:
1. ubuntu PPA 更新老是不成功该怎么办2. docker网络端口映射,没有方便点的操作方法么?3. mysql - 这条sql语句为什么加上where就报错?4. angular.js - angular内容过长展开收起效果5. jquery - 移动端如何写弹性效果6. python爬虫 - scrapy使用redis的时候,redis需要进行一些设置吗?7. javascript - 三目运算符的一些问题8. android-studio - Android Studio编译出错9. nginx - 关于javaweb项目瘦身问题,前期开发后,发现项目占用存贮空间太大,差不多1.2个G,怎么实现瘦身,动态页面主要是jsp。10. 请教关于jquery阻止冒泡的问题?

网公网安备