我有
<div style="position:relative; width:500px;">
<div style="position:absolute; width:100%"></div>
</div>
子div占用其父div的100%宽度。有没有办法可以强制它采取100%宽度的身体而不是父div。我需要在上面的代码中进行相对和绝对定位。
答案 0 :(得分:2)
在保持代码中相对和绝对定位的同时执行此操作的唯一方法是使用JavaScript。您需要获取窗口宽度并将其设置为div宽度。您还需要在调整大小时检测窗口大小,以便始终将div调整设置为当前窗口宽度。
你可以做的其他两种方式可能不是选择,但值得一提
答案 1 :(得分:0)
现代浏览器support的viewport units。
header {
width: 50%;
background-color: lightblue;
padding: 20px 0;
}
nav {
width: 100vw;
background-color: orange;
padding: 20px 0;
}
<html>
<body>
<header>
<p>This inherits the width of the parent like normal.</p>
<nav>
<a href="/">this fills the viewport</a>
</nav>
</header>
</body>
</html>