如何給行內元素設置寬高?

前言

在實際開發中,咱們不可避免的有時須要給行內元素設置寬高,那麼如何來實現呢?工具

方法一:使用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>

效果圖:flex

方法二:使用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>

效果圖:spa

方法三:使用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,也就是說以上三種方法的原理是一致的。 code

相關文章
相關標籤/搜索