前言
在實際開發中,我們不可避免的有時需要給行內元素設置寬高,那么如何來實現呢?
方法一:使用display
display:block/inline-block/flex/inline-flex
<style> * { list-style: none; border: 0; padding: 0; margin: 0 } span { width: 100px; height: 100px; background: red; text-align: center; line-height: 100px; display: block/inline-block/flex/inline-flex; } </style> <span>1</span>
效果圖:
方法二:使用position
position:absolute/fixed
<style> * { list-style: none; border: 0; padding: 0; margin: 0 } span { width: 100px; height: 100px; background: red; text-align: center; line-height: 100px; position:absolate/fixed; } </style> <span>1</span>
效果圖:
方法三:使用float
float:left/right
<style> * { list-style: none; border: 0; padding: 0; margin: 0 } span { width: 100px; height: 100px; background: red; text-align: center; line-height: 100px; float:left/right; } </style> <span>1</span>
效果圖:
使用position和float的原因
解析:通過調試工具不難發現,float和position方法有一個共同的表現:display:block,這不是偷偷的把行內元素變為塊級元素了嗎?其實就算將display設置為flex/inline-flex/inline-block,在computed中查看display會發現屬性值也為block,也就是說以上三種方法的原理是一致的。