css 控制图片的横竖比例

大概你也遇到过"图片高度是宽度50%"这的需求
这需求看起来简单, 其实却非常麻烦

因为元素的宽高的百分比是相对于父元素的宽高计算的
所以直接设 width, height 是不符合预期的

.div {
    
    
	width: 100%;
	height: 50%;
}

而且一个空 display: block 元素 height 的默认值是 0px; 如果父元素没设 height 的话, 该元素的 height 就是 0px


如果是位置比较浅的元素, 其实可以用 css3 的新单位 vw, vh 来实现

.img {
    
    
	width: 100vw;
	height: 50vw;
}
.img {
    
    
	width: 100vh;
	height: 50vh;
}

但如果是位置比较深的元素, 那么比率就会难以计算
vw, vh 也难以实现这个需求


这个时候我们就可以利用 padding 了, 因为 padding 的百分比是相对于父元素的宽计算的, 这样纵向和横向就能统一

.div {
    
    
	width: 100%;
	padding-bottom: 50%;
	height: 0;
}

目前我们已经可以实现固定横竖比例的元素
结合 position: relative; position: absolute; 就可以拓展到固定横竖比例的图片

<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8" />
	<title>css 控制图片的横竖比例</title>
	<style>
		* {
     
     
			outline: 1px #f00 solid;
		}

		.ratioImg {
     
     
			width: 50%;
			height: auto;
			/* 高度自动; 宽度自定义 */
		}

		.ratioImg__box {
     
     
			width: 100%;
			padding-bottom: 50%;
			position: relative;
			height: 0;
		}

		.ratioImg__box__img {
     
     
			position: absolute;
			top: 0;
			left: 0;
			/* bottom: 0; */
			/* right: 0; */
			/* margin: auto; */
			display: block;
			width: 100%;
			height: 100%;
		}
	</style>
</head>

<body>
	<div class="ratioImg">
		<div class="ratioImg__box">
			<img class="ratioImg__box__img" src="https://profile.csdnimg.cn/F/A/9/3_u013970232" />
		</div>
	</div>
</body>

</html>

//end

猜你喜欢

转载自blog.csdn.net/u013970232/article/details/111059967