Html 更改窗口宽度\高度时自动调整大小的 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18666106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A div with auto resize when changing window width\height
提问by Urbanleg
I've looked everywhere . and still couldn't come up with sample code of a very "basic" idea:
我到处找。并且仍然无法想出一个非常“基本”的想法的示例代码:
A div that is taking 90% of the screen size and it is adjusting itself whenever the browser size changes (to take 90% of the relative screen)
一个 div 占据屏幕大小的 90%,并且在浏览器大小发生变化时进行自我调整(占据相对屏幕的 90%)
The nested divs inside it should resize themselves as well.
它里面的嵌套 div 也应该调整自己的大小。
Is it even possible?
甚至有可能吗?
EDIT:
编辑:
Width 90% is not working when I try to re size the screen vertically.
当我尝试垂直调整屏幕大小时,宽度 90% 不起作用。
回答by Eric Warnke
Use vh attributes. It means viewport height and is a percentage. So height: 90vh would mean 90% of the viewport height. This works in most modern browsers.
使用 vh 属性。它表示视口高度,是一个百分比。所以 height: 90vh 意味着视口高度的 90%。这适用于大多数现代浏览器。
Eg.
例如。
div {
height: 90vh;
}
You can forego the rest of your silly 100% stuff on the body.
你可以放弃身体上其他愚蠢的 100% 东西。
If you have a header you can also do some fun things like take it into account by using the calc function in CSS.
如果你有一个标题,你也可以做一些有趣的事情,比如通过使用 CSS 中的 calc 函数来考虑它。
Eg.
例如。
div {
height: calc(100vh - 50px);
}
This will give you 100% of the viewport height, minus 50px for your header.
这将为您提供 100% 的视口高度,为您的标题减去 50px。
回答by insertusernamehere
In this scenario, the outer <div>
has a width and height of 90%. The inner div>
has a width of 100% of its parent. Both scale when re-sizing the window.
在这种情况下,外部<div>
的宽度和高度为 90%。内部div>
的宽度是其父级的 100%。重新调整窗口大小时两者都会缩放。
HTML
HTML
<div>
<div>Hello there</div>
</div>
CSS
CSS
html, body {
width: 100%;
height: 100%;
}
body > div {
width: 90%;
height: 100%;
background: green;
}
body > div > div {
width: 100%;
background: red;
}
Demo
演示
回答by Racharla Sruthi
<!DOCTYPE html>
<html>
<head>
<style>
div {
padding: 20px;
resize: both;
overflow: auto;
}
img{
height: 100%;
width: 100%;
object-fit: contain;
}
</style>
</head>
<body>
<h1>The resize Property</h1>
<div>
<p>Let the user resize both the height and the width of this 1234567891011 div
element.
</p>
<p>To resize: Click and drag the bottom right corner of this div element.</p>
<img src="images/scenery.jpg" alt="Italian ">
</div>
<p><b>Note:</b> Internet Explorer does not support the resize property.</p>
</body>
</html>
回答by muskan
Code Snippet:
代码片段:
div{height: calc(100vh - 10vmax)}