最大化视口中心的DIV,但保持宽高比
这就是我正在寻找的:
根据视口大小调整大小,但始终保持其纵横比。这就是我已经走了多远:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Example</title>
</head>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
background-color: red;
}
div#content {
margin: auto;
width: 100vmin;
height: 100vmin;
background-color: blue;
}
</style>
<body>
<div id="content"></div>
</body>
</html>
居中并最大化,但其宽高比始终为 1:1。例如,如果我想要 2:1,该怎么办?This is what I'm looking for:
The <div>
adjusts in size depending on the viewport size, but it always keeps its aspect ratio.
This is how far I've come:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Example</title>
</head>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
background-color: red;
}
div#content {
margin: auto;
width: 100vmin;
height: 100vmin;
background-color: blue;
}
</style>
<body>
<div id="content"></div>
</body>
</html>
The <div>
is centered and maxed, but it always has 1:1 aspect ratio. What do I do if I want 2:1 for example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为我通过组合
最大宽度
和max-height
来解决它。以下是2:1纵横比的示例。首先,我们希望
宽度:100VW
以填充完整宽度,并且(由于2:1)高度
一半,所以高度:50VW
。但是,如果视口宽度变得更宽并且视口高度降低,则在某个时候50VW
将大于视口高。这由Max-Height涵盖:100VH
。因此,高度永远不会比视口高。宽度相同的作品:最大宽度:200VH
将宽度限制为两倍(由于2:1)的高度最大大小,即100VH
。对于4:3的纵横比,它将为3/4 = 0.75
高度:75VW
和4/3 = 1.33最大宽度:133VH
等等。I think I managed to solve it by combining
max-width
andmax-height
.Below is an example for 2:1 aspect ratio. First, we want
width: 100vw
to fill the full width and (due to 2:1)height
half of that, soheight: 50vw
. However, if the viewport width gets wider and viewport height decreases, at some point50vw
is going to be bigger than the viewport height. This is covered bymax-height: 100vh
. So the height never gets bigger than the viewport height. The same works for the width:max-width: 200vh
limits the width to double (due to 2:1) the maximum size of the height, which was100vh
.For 4:3 aspect ratio, it would be 3/4=0.75
height: 75vw
and 4/3=1.33max-width: 133vh
and so on.