是否可以在CSS中设置任何变量,例如希望div高度始终为div的一半,而div的屏幕尺寸宽度以百分比为单位?
<div class="ss"></div>
CSS:
.ss {
width:30%;
height: half of the width;
}
30%的宽度随屏幕分辨率缩放
Answers:
您可以借助对父项的填充来完成此操作,因为相对填充(甚至高度)是基于父元素的宽度的。
CSS:
.imageContainer {
position: relative;
width: 25%;
padding-bottom: 25%;
float: left;
height: 0;
}
img {
width: 100%;
height: 100%;
position: absolute;
left: 0;
}
这是基于本文的: 仅使用CSS的比例缩放响应框
实现此目的的另一种好方法是使用具有设定纵横比的透明图像。然后将图像的宽度设置为100%,将高度设置为自动。不幸的是,这将降低容器的原始内容。因此,您需要将原始内容包装在另一个div中,并将其绝对定位在父div的顶部。
<div class="parent">
<img class="aspect-ratio" src="images/aspect-ratio.png" />
<div class="content">Content</div>
</div>
的CSS
.parent {
position: relative;
}
.aspect-ratio {
width: 100%;
height: auto;
}
.content {
position: absolute;
width: 100%;
top: 0; left: 0;
}
height: 100%;
在.content
。谢谢你的小费。我比填充更喜欢这种方法。
如果要与封闭div上以像素为单位设置的宽度成比例的垂直大小调整,我相信您需要一个额外的元素,如下所示:
#html
<div class="ptest">
<div class="ptest-wrap">
<div class="ptest-inner">
Put content here
</div>
</div>
</div>
#css
.ptest {
width: 200px;
position: relative;
}
.ptest-wrap {
padding-top: 60%;
}
.ptest-inner {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: #333;
}
这是无效的2 div解决方案。请注意,垂直填充的60%与窗口宽度成正比,而不与div.ptest
宽度成正比:
这是上面的代码可以正常工作的示例:
这个答案与其他答案基本相同,但我不希望使用太多的类名。但这只是个人喜好。您可能会争辩说,在每个div上使用类名更加透明,因为预先声明了嵌套div的目的。
<div id="MyDiv" class="proportional">
<div>
<div>
<p>Content</p>
</div>
</div>
</div>
这是通用CSS:
.proportional { position:relative; }
.proportional > div > div { position:absolute; top:0px; bottom:0px; left:0px; right:0px; }
然后定位第一个内部div以设置宽度和高度(padding-top):
#MyDiv > div { width:200px; padding-top:50%; }
处理图像时有用的一种方法,但在其他情况下也可以用作解决方法:
<html>
<head>
</head>
<style>
#someContainer {
width:50%;
position: relative;
}
#par {
width: 100%;
background-color:red;
}
#image {
width: 100%;
visibility: hidden;
}
#myContent {
position:absolute;
}
</style>
<div id="someContainer">
<div id="par">
<div id="myContent">
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
</div>
<img src="yourImage" id="image"/>
</div>
</div>
</html>
要使用您的图片网址替换yourImage。您可以使用所需的宽高比的图像。
div id =“ myContent”是解决方法的示例,其中myContent将覆盖在图像上。
就像这样:父div将采用图像的高度,图像高度将采用父的宽度。但是图像被隐藏。