gpt4 book ai didi

html - 响应式纵横比与纯 css : how to fill container's height?

转载 作者:行者123 更新时间:2023-11-28 15:15:31 25 4
gpt4 key购买 nike

我希望内部 div 填充容器的高度,同时保持 1:1 的固定纵横比。

实现固定宽高比的常用技巧是利用填充:实际上,当声明填充的百分比而不是固定值时,百分比是根据相关元素的宽度计算的,即使我们声明的是垂直padding-top 或 padding-bottom 等值。

如果你想填充容器的宽度,这使得填充成为一个很好的利用技巧,但如果你想填充容器的高度则不行。

是否可以仅使用 CSS 来实现它?没有 JavaScript,谢谢。

理想情况下,我希望 CSS 单元与视口(viewport)单元互补,但相对于容器而言。像这样的东西:

  • cw(容器宽度)
  • ch(容器高度)
  • cmin(容器最小值)
  • cmax(容器最大值)

会非常棒。

<!DOCTYPE html>
<html>

<head>
<style>
.container {
background-color: green;
height: 30vh;
}

.fixed-aspect-ratio {
background-color: red;
width: 100%;
padding-top: 100%;
/* 1:1 Aspect Ratio */
position: relative;
/* If you want text inside of it */
}
/* If you want text inside of the container */

.text {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
</style>
</head>

<body>
<div class="container">
<div class="fixed-aspect-ratio">
<div class="text">Some text</div>
<!-- If you want text inside the container -->
</div>
</div>
</body>

</html>

https://www.w3schools.com/code/tryit.asp?filename=FLJBS4J2MTWS

最佳答案

高度没有类似的 CSS 解决方案,宽度为 padding-bottom

除了脚本之外,这是我用过的一个技巧,我在其中放置了一个 img,带有一个数据 url SVG(也可以是 Base64 png)以避免额外的服务器往返, 正方形。

通过将其高度设置为 100%,它将保留其父级,即内联 block ,一个正方形,并使用 visibility: hidden 隐藏它。

堆栈片段

.container {
background-color: green;
height: 50vh;
}

.fixed-aspect-ratio {
display: inline-block;
background-color: red;
height: 100%;
position: relative;
}

.fixed-aspect-ratio img {
display: block;
height: 100%;
visibility: hidden;
}

.text {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
<div class="container">
<div class="fixed-aspect-ratio">
<img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><rect width='10' height='10'/></svg>">
<div class="text">Some text</div>
<!-- If you want text inside the container -->
</div>
</div>

关于html - 响应式纵横比与纯 css : how to fill container's height?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47314956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com