搜索
javascript - 为何margin:auto auto 不能上下左右对齐?
过去多啦不再A梦
过去多啦不再A梦 2017-06-24 09:42:38
[CSS3讨论组]

一个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;不能上下左右居中?? 
过去多啦不再A梦
过去多啦不再A梦

全部回复(4)
大家讲道理

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规范

阿神

这是个好问题,那我问你,当一行存在两个元素的时候,你可以左右居中吗?同理当你的上下都可能有元素存在的情况下你要浏览器怎么去计算对应元素应该存在的位置?

某草草

不能吧,上下对齐如果不用flex布局,没啥太好的办法。virtical–align也不太好用!

PHP中文网

不能,如果想上下左右对居中的话,推荐使用flex布局,其次是table,table-cell或者定位

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号