CSS保持元素宽高比,固定元素宽高比

方法一:

html 复制代码
<div class="hcp-fixed-aspect-ratio-box">
	这里是正文内容
</div>
css 复制代码
.hcp-fixed-aspect-ratio-box {
	width: 50%;
	color: #FFFFFF;
	margin: 100px auto;
	background: #FF0000;
	/* 宽高比2:1,兼容性可能不太好 */
	aspect-ratio: 2 / 1;
}

方法二:

html 复制代码
<div class="hcp-fixed-aspect-ratio-box">
	<div class="hcp-inner">
		<div class="hcp-content">
			这里是正文内容
		</div>
	</div>
</div>
css 复制代码
.hcp-fixed-aspect-ratio-box {
	width: 50%;
	margin: 100px auto;
	background: #FF0000;
}
.hcp-fixed-aspect-ratio-box .hcp-inner {
	height: 0;
	width: 100%;
	/* 
	padding在各个方向中的中的百分比,都是相较于父元素宽度的
	所以这里设置padding-top为50%,就将其高度撑开到了父元素宽度的50%
	它自身高度为0,加上padding-top的高度,总体高度就是其父元素宽度的50%
	 */
	padding-top: 50%;
	/* 然后使用相对定位 */
	position: relative;
}
.hcp-fixed-aspect-ratio-box .hcp-content {
	/* 设置其宽高与父元素相同 */
	width: 100%;
	height: 100%;
	color: #FFFFFF;
	/* 然后使用绝对定位 */
	top: 0;
	left: 0;
	position: absolute;
}
相关推荐
_23331 天前
vue3二次封装element-plus表格,slot透传,动态slot。
前端·vue.js
jump6801 天前
js中数组详解
前端·面试
崽崽长肉肉1 天前
iOS 基于Vision.framework从图片中提取文字
前端
温宇飞1 天前
Web Abort API - AbortSignal 与 AbortController
前端
Tomoon1 天前
前端开发者的全栈逆袭
前端
Filotimo_1 天前
2.CSS3.(3).html
前端·css3
whyfail1 天前
React v19.2版本
前端·javascript·react.js
慧慧吖@1 天前
react基础
前端·javascript·react.js
浪裡遊1 天前
MUI组件库与主题系统全面指南
开发语言·前端·javascript·vue.js·react.js·前端框架·node.js