前言
在开发中,我们有时需要给行内元素设置宽高,如何来实现呢?
方法一:使用display
display:block/inline-block/flex/inline-flex
见代码:
span {
width: 100px;
height: 100px;
background: red;
text-align: center;
line-height: 100px;
display: block;
}
<span>1</span>

方法二:使用position
position:absolute/fixed
见代码:
span {
width: 100px;
height: 100px;
background: red;
text-align: center;
line-height: 100px;
position: absolute;
}
<span>1</span>

方法三:使用float
float:left/right
见代码:
span {
width: 100px;
height: 100px;
background: red;
text-align: center;
line-height: 100px;
float:left;
}
<span>1</span>

使用position和float能设置宽高的原因
通过调试工具不难发现,float和position方法有一个共同的表现:display:block。其实就算将display设置为flex/inline-flex/inline-block,在computed中查看display会发现属性值也为block,也就是说以上三种方法的原理是一致的。

网友评论