如何给行内元素设置宽高?

前言

在实际开发中,我们不可避免的有时需要给行内元素设置宽高,那么如何来实现呢?

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

猜你喜欢

转载自www.cnblogs.com/kunmomo/p/10792968.html