css 实现image宽度百分百,高度跟宽度一样大小

前言:第一次写博客(不知道从何说起),希望以后再接再励。之前也遇到很多问题,有总结过,但是没有写出来(改天继续贴出其他总结),今天遇见css 实现image宽度百分百,高度跟宽度一样大小这个问题。贴出解决方案一个

1、写两个div盒子,父子关系

<div class="image">
<img :src="food.image">
</div>

2、样式方面(less语法)

.image{
position: relative;
width: 100%;
height: 0px;
padding-top: 100%; //padding-bottom都可以
img{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
}

3、原理:外层div中,padding-top:100%;(padding-bottom)这个padding-top(padding-bottom)中的百分百是根据width去计算的,所以padding-top拿到了跟width一样的大小,又通过padding去填充了容器的高度,所以实现了div宽度百分百,高度跟宽度一样大小;内部img标签的position:absolute。使其成为块状元素,可以设置img宽高,均为外层div盒子的百分百,由此实现image宽度百分百,高度跟宽度一样大小

猜你喜欢

转载自blog.csdn.net/gzyzwx/article/details/76039213
今日推荐