ily*_*lyo 216 html css responsive-design
当我给图像一个百分比的宽度或高度时,它只会增长/缩小保持其纵横比,但如果我想要与另一个元素相同的效果,是否可以使用百分比将宽度和高度联系在一起?
Chr*_*ris 528
你可以使用纯CSS做到这一点; 不需要JavaScript.这利用了(有点违反直觉的)事实,即padding-top
百分比是相对于包含块的宽度.这是一个例子:
.wrapper {
width: 50%;
/* whatever width you want */
display: inline-block;
position: relative;
}
.wrapper:after {
padding-top: 56.25%;
/* 16:9 ratio */
display: block;
content: '';
}
.main {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
/* fill parent */
background-color: deepskyblue;
/* let's see it! */
color: white;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
<div class="main">
This is your div with the specified aspect ratio.
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
Tom*_*der 44
扼杀Chris的想法,另一种选择是使用伪元素,因此您不需要使用绝对定位的内部元素.
<style>
.square {
/* width within the parent.
can be any percentage. */
width: 100%;
}
.square:before {
content: "";
float: left;
/* essentially the aspect ratio. 100% means the
div will remain 100% as tall as it is wide, or
square in other words. */
padding-bottom: 100%;
}
/* this is a clearfix. you can use whatever
clearfix you usually use, add
overflow:hidden to the parent element,
or simply float the parent container. */
.square:after {
content: "";
display: table;
clear: both;
}
</style>
<div class="square">
<h1>Square</h1>
<p>This div will maintain its aspect ratio.</p>
</div>
Run Code Online (Sandbox Code Playgroud)
我在这里放了一个演示:http://codepen.io/tcmulder/pen/iqnDr
Isa*_*aac 30
<style>
#aspectRatio
{
position:fixed;
left:0px;
top:0px;
width:60vw;
height:40vw;
border:1px solid;
font-size:10vw;
}
</style>
<body>
<div id="aspectRatio">Aspect Ratio?</div>
</body>
Run Code Online (Sandbox Code Playgroud)
这里需要注意的关键是vw
=视口宽度和vh
=视口高度