前言
hello world欢迎来到前端的新世界
😜当前文章系列专栏:Sass和Less
🐱👓博主在前端领域还有很多知识和技术需要掌握,正在不断努力填补技术短板。(如果出现错误,感谢大家指出)🌹
💖感谢大家支持!您的观看就是作者创作的动力
先上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
width:400px;
height:500px;
resize: both;
overflow: hidden;
padding:10px;
background-color: aqua;
container-type:inline-size;
}
div p{
font-size: 5cqh;
}
</style>
</head>
<body>
<div>
<p>你好</p>
</div>
</body>
</html>
容器查询
在 CSS 中,容器查询(Container Queries)是一种允许样式根据其父容器尺寸变化而改变的功能。然而,目前 CSS 规范中还没有原生支持容器查询的功能,因此暂时无法直接使用 cqw 和 cqh。
缺点:兼容性不好
js模拟实现
<!DOCTYPE html>
<html>
<head>
<style>
.container {
width: 300px;
height: 200px;
background-color: lightblue;
}
.container[data-cqw="small"] {
background-color: lightgreen;
}
.container[data-cqh="tall"] {
background-color: lightpink;
}
</style>
</head>
<body>
<div class="container" id="myContainer">
<!-- 这里是容器的内容 -->
</div>
<script>
const container = document.getElementById('myContainer');
const resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
const { width, height } = entry.contentRect;
// 根据容器尺寸应用相应的样式
container.setAttribute('data-cqw', width <= 300 ? 'small' : 'large');
container.setAttribute('data-cqh', height <= 200 ? 'short' : 'tall');
}
});
resizeObserver.observe(container);
</script>
</body>
</html>
后言
创作不易,要是本文章对广大读者有那么一点点帮助 不妨三连支持一下,您的鼓励就是博主创作的动力