gpt4 book ai didi

css - 将 div 宽度设置为高度的百分比

转载 作者:行者123 更新时间:2023-12-04 08:46:18 24 4
gpt4 key购买 nike

我正在尝试设置 .full_height_div 的宽度元素使用纯 css,基于其高度。它必须是宽度相对于高度,而不是高度相对于宽度。这样做的原因是父容器( .set_rectangle_height )已经是一个高度相对于页面宽度的 div。显然,随着页面大小调整,div页面上的 s 将调整大小,因此我无法在 px 中设置固定宽度为 .full_height_div child 。

所以.rectangle.set_rectangle_height组成父容器,其宽度占页面的百分比,高度相对于该宽度。见 here对这种方法的解释。

但问题是我想用 height: 100% 在父级内部放置一个 div和相对于这个高度的宽度。目标是我将能够更改浏览器窗口大小,并且所有内容都将保持其纵横比。

here is my failed attempt:

.rectangle
{
position: relative;
width: 30%;/*the outermost div is always a % of the page
width, even while resizing*/
display:inline-block;
background-color: green;
}
.set_rectangle_height
{
padding-bottom: 30%;/*this sets the height of the outermost div
to a ratio of 1:3*/
position: relative;
float: left;
width: 100%;
height: 100%;
}
.full_height_div/*this is the div that i want to have a width relative
to its height*/
{
height: 100%;
width: 20px;/*i will delete this once .square_set_width is working*/
position: absolute;
background-color: red;
}
.square_set_width
{
display: inline-block;
padding-left: 100%; /*i want to use something like this line to set
the width of this div to be equal to .full_height_div's height - ie a 1:1 aspect
ratio, but padding-left does not work :( */
position: relative;
height: 100%;
background-color: blue;
}

<div class='rectangle'>
<div class='set_rectangle_height'>
<div class='full_height_div'>
<div class='square_set_width'></div>
</div>
</div>
</div>

所以,这就是上面不正确的标记的样子:

incorrect layout

这就是我想要的样子:

correct layout

我知道我可以在 javascript 中找到蓝色的平方百分比高度,然后将宽度设置为等于这个高度,但是如果我想要做的事情有一个纯 css 修复,那将非常方便。我会经常使用这种结构,而且我真的不想编写代码来调整页面上所有 div 的大小。

最佳答案

你必须为此使用javascript。如果我理解你,你想要一个完美的蓝色方块。用

var height = $('.square_set_width').height();
$('.square_set_width').css('width',height);

这是一个 jsfiddle: http://jsfiddle.net/a8kxu/

编辑:而不是做 padding-bottom: 30%height: 70%反而。这是另一个 fiddle : http://jsfiddle.net/a8kxu/1/

编辑 #2:抱歉,您不能使用 css 来执行此操作。它不够强大

关于css - 将 div 宽度设置为高度的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15582927/

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