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.
下面是關(guān)于高度的:
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:
因為規(guī)范就是這么規(guī)定的算法,瀏覽器就是這么實現(xiàn)的。
CSS規(guī)范
回答2:這是個好問題,那我問你,當(dāng)一行存在兩個元素的時候,你可以左右居中嗎?同理當(dāng)你的上下都可能有元素存在的情況下你要瀏覽器怎么去計算對應(yīng)元素應(yīng)該存在的位置?
回答3:不能吧,上下對齊如果不用flex布局,沒啥太好的辦法。virtical–align也不太好用!
回答4:不能,如果想上下左右對居中的話,推薦使用flex布局,其次是table,table-cell或者定位
相關(guān)文章:
1. 在應(yīng)用配置文件 app.php 中找不到’route_check_cache’配置項2. html按鍵開關(guān)如何提交我想需要的值到數(shù)據(jù)庫3. HTML 5輸入框只能輸入漢字、字母、數(shù)字、標(biāo)點符號?正則如何寫?4. javascript - 請教如何獲取百度貼吧新增的兩個加密參數(shù)5. gvim - 誰有vim里CSS的Indent文件, 能縮進(jìn)@media里面的6. 跟著課件一模一樣的操作使用tp6,出現(xiàn)了錯誤7. PHP類屬性聲明?8. javascript - JS請求報錯:Unexpected token T in JSON at position 09. objective-c - ios 怎么實現(xiàn)微信聯(lián)系列表 最好是swift10. java - 安卓接入微信登錄,onCreate不會執(zhí)行
