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. mysql - 數據庫建字段,默認值空和empty string有什么區別 1102. 新人求教MySQL關于判斷后拼接條件進行查詢的sql語句3. 在mybatis使用mysql的ON DUPLICATE KEY UPDATE語法實現存在即更新應該使用哪個標簽?4. mysql - 這種分級一對多,且分級不平衡的模型該怎么設計表?5. Navicat for mysql 中以json格式儲存的數據存在大量反斜杠,如何去除?6. mysql - 數據庫表中,兩個表互為外鍵參考如何解決7. php - 公眾號文章底部的小程序二維碼如何統計?8. mysql - 表名稱前綴到底有啥用?9. mysql - 千萬數據 分頁,當偏移量 原來越大時,怎么優化速度10. mac OSX10.12.4 (16E195)下Mysql 5.7.18找不到配置文件my.cnf
