使用百分比高度时 div 定位不正确
Incorrect positioning of divs when using height in percentage
我不确定这个问题以前有没有发过,但我不知道如何有效地提出这个问题。
在我的网站上,我创建了两个大版块一个接一个(不是指标签),一个高度设置为 100%,另一个设置为 90%。我在第二部分的正下方添加了一个 div。为了保持 div 卡住,我将 "top" 设置为 190% 以模拟两个部分的长度。尽管我为每个部分设置了最小高度,这使得 div 在停止调整大小时在部分下方爬行。
如何在对元素使用 "position: absolute" 时避免这种情况?
html 示例(使用一个较大的部分):
<html>
<body>
<div class="section1"></div>
<div class="box"></div>
</body>
</html>
css 示例:
.section1 {
display: inline-block; width: 100%; height: 100%; min-height: 500px;
position: absolute;
}
.box {
width: 100%; height: 200px;
position: absolute; top: 100%; margin-top: 50px;
}
谢谢,
乔纳森
只是不要使用 position:absolute
。
我假设你拥有它的原因是因为你需要视口的 100% 高度,而不使用 JS。您可以使用 vh
单位,但它没有最好的 support/reliability.
最简单的方法是简单地将html
和body
设置为height:100%;
:
body,
html {
margin: 0;
height: 100%;
}
.full {
height: 100%;
background: teal;
}
.shorter {
height: 90%;
background: #fbfbfb;
}
footer {
background: #222021;
color: white;
text-align: center;
padding: 10px;
}
<section class="full"></section>
<section class="shorter"></section>
<footer>Made with love by a kitten</footer>
请注意,我确实添加了额外的 CSS 用于样式设置。
我不确定这个问题以前有没有发过,但我不知道如何有效地提出这个问题。
在我的网站上,我创建了两个大版块一个接一个(不是指标签),一个高度设置为 100%,另一个设置为 90%。我在第二部分的正下方添加了一个 div。为了保持 div 卡住,我将 "top" 设置为 190% 以模拟两个部分的长度。尽管我为每个部分设置了最小高度,这使得 div 在停止调整大小时在部分下方爬行。
如何在对元素使用 "position: absolute" 时避免这种情况?
html 示例(使用一个较大的部分):
<html>
<body>
<div class="section1"></div>
<div class="box"></div>
</body>
</html>
css 示例:
.section1 {
display: inline-block; width: 100%; height: 100%; min-height: 500px;
position: absolute;
}
.box {
width: 100%; height: 200px;
position: absolute; top: 100%; margin-top: 50px;
}
谢谢,
乔纳森
只是不要使用 position:absolute
。
我假设你拥有它的原因是因为你需要视口的 100% 高度,而不使用 JS。您可以使用 vh
单位,但它没有最好的 support/reliability.
最简单的方法是简单地将html
和body
设置为height:100%;
:
body,
html {
margin: 0;
height: 100%;
}
.full {
height: 100%;
background: teal;
}
.shorter {
height: 90%;
background: #fbfbfb;
}
footer {
background: #222021;
color: white;
text-align: center;
padding: 10px;
}
<section class="full"></section>
<section class="shorter"></section>
<footer>Made with love by a kitten</footer>
请注意,我确实添加了额外的 CSS 用于样式设置。