css controls the horizontal and vertical ratio of the picture

Probably you have also encountered the requirement of "image height is 50% of width".
This requirement looks simple, but in fact it is very troublesome

Because the percentage of the
width and height of the element is calculated relative to the width and height of the parent element, setting the width and height directly does not meet expectations.

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

And the default value of the height of an empty display: block element is 0px; if the parent element does not set the height, the height of the element is 0px


If it is a relatively shallow element, you can actually use the new unit vw, vh of css3 to achieve

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

But if it is a relatively deep element, then the ratio will be difficult to calculate
vw, and vh is also difficult to achieve this demand.


At this time, we can use padding, because the percentage of padding is calculated relative to the width of the parent element, so that the vertical and horizontal directions can be unified

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

At present, we can already achieve fixed horizontal and vertical ratio elements,
combined with position: relative; position: absolute; can be extended to fixed horizontal and vertical ratio pictures

<!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

Guess you like

Origin blog.csdn.net/u013970232/article/details/111059967