如何获取包含块之外的祖先元素的宽高
一、使用css变量
css
.container {
width: 200px;
height: 100px;
background-color: #f0f0f0;
--ancestor-width: 200px;
--ancestor-height: 100px;
}
.box {
width: 150px;
height: 50px;
background-color: #000;
}
.item {
width: var(--ancestor-width);
height: var(--ancestor-height);
background-color: red;
}
当祖先元素的宽高是百分比的时候还是挺有用的
二、使用容器查询
css
/*
方案1: 使用容器查询获取祖先元素宽度(推荐,现代浏览器)
将祖先元素设置为容器
*/
.container {
container-type: inline-size;
width: 200px;
height: 100px;
background-color: #f0f0f0;
}
.box {
width: 150px;
height: 50px;
background-color: #000;
}
.item {
/* 方案1: 使用容器查询(推荐)- 基于祖先容器宽度
65cqw = 65% of container width (祖先元素.su-content的宽度) */
width: 65cqw;
height: 100%;
background-color: red;
}