我已经到处找过了,但仍然找不到一个非常“基础”的想法的示例代码:
一个div占屏幕大小的90%,并在浏览器大小更改时自动调整自身(以占据相对屏幕的90%)
其中嵌套的div也应该自动调整大小。
这是否可能?
编辑:
垂直重新调整屏幕大小时,宽度90%无法正常工作。
我已经到处找过了,但仍然找不到一个非常“基础”的想法的示例代码:
一个div占屏幕大小的90%,并在浏览器大小更改时自动调整自身(以占据相对屏幕的90%)
其中嵌套的div也应该自动调整大小。
这是否可能?
编辑:
垂直重新调整屏幕大小时,宽度90%无法正常工作。
使用vh属性。它表示视口高度并以百分比表示。因此height:90vh表示视口高度的90%。这在大多数现代浏览器中都有效。
例如。
div {
height: 90vh;
}
你可以省略身体部分其他无意义的100%内容。
如果你有一个页眉,你也可以通过在CSS中使用calc函数来考虑它,这样做会很有趣。
例如:
div {
height: calc(100vh - 50px);
}
这将为您提供100%的视口高度,减去50像素用于您的页眉。
<div>
宽度和高度为 90%。内部的 <div>
宽度为其父元素的 100%。在重新调整窗口大小时,两者都会按比例缩放。
HTML
<div>
<div>Hello there</div>
</div>
CSS
html, body {
width: 100%;
height: 100%;
}
body > div {
width: 90%;
height: 100%;
background: green;
}
body > div > div {
width: 100%;
background: red;
}
Demo
我正在寻找类似的解决方案,我认为在处理动态变化时最好使用JavaScript。
我渲染了两个div,一个在外面,一个在里面,根据屏幕宽度设置外部div的高度/宽度(基于1500像素宽度100像素的外部div)。对于内部div,我根据外部div的百分比进行计算。
<div class="wrapper">
<div class="box outer">
<div class="box inner"></div>
</div>
</div>
.wrapper{
/* not important just to make the box appear in center for visibility*/
display: block;
margin: 200px auto;
width: fit-content;
}
/*Only selecting background colors and making inner box adjust in the center of outer box*/
.box.outer {
background: rgb(204, 75, 25);
position: relative;
}
.box.inner {
background: green;
position: absolute;
top:50%; left:50%; transform: translate(-50%, -50%);
}
document.addEventListener("DOMContentLoaded", function (event) {
let outerBox = document.querySelector('.box.outer');
let innerBox = document.querySelector('.box.inner');
// multiplier is used to calculate width of inner div based on outer div, so they always look the same shape
let multiplier = 0.8;
function renderBox() {
//let outerbox Dimension based on window width assuming 1500px width as base
outerBox.style.height = window.innerWidth / 15 + 'px';
outerBox.style.width = outerBox.style.height;
innerBox.style.height = outerBox.offsetHeight * multiplier + 'px';
innerBox.style.width = outerBox.offsetHeight * multiplier + 'px';
}
window.addEventListener("load", function (e) {
renderBox();
})
window.addEventListener('resize', function (e) {
renderBox();
})
})
<!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>
div{height: calc(100vh - 10vmax)}
<div style="width: 90%;"><div style="width: 60%;"></div><div style="width: 40%;"></div></div>
- tomaroowidth: 90%; height:90%
是你要找的吗? - user1618143