如何根据浏览器高度制作“边距:顶部”

How to make `margin: top;` based on browser height?

本文关键字:边距 顶部 何根 浏览器 高度      更新时间:2023-09-26

标题几乎说明了一切。我希望我的 HTML main_content 元素上的 CSS margin: top;相对于浏览器窗口(百分比)(以便main_content始终保持在浏览器窗口的底部。我怎样才能做到这一点?


我试过这个,但它不起作用。(body {height:100vh}似乎没有使body有任何高度,因为main_content不会像它应该的那样粘在底部。

body {height:100vh}
#main_content {position:absolute; width:100%; display:block; left:0; bottom:0; text-align:center; padding:20px;}
<div>Extra Infomation </div>
<div id="main_content">
<p>here you can learn about me and my adventures</p>
</div>

(现在不要尝试这个)如果你去我的网站,你会看到"了解我和我的冒险"标题,连同"最近的活动",以及下面的其他内容,这就是我想要在浏览器窗口底部的部分,最好是"了解我和我的冒险"部分只是从页面底部伸出来。

给.main_content一个 100vh 的边距顶部(就在视口下方),然后使用 transformY 将其拉回:

.main_content {
    text-align: center;
    padding: 20px;
    margin-top: 100vh;
    transform: translateY(calc(-100% - 20px));
	background:lightblue;
}
.below_content{
	margin-top:-100px;
}
<div class="wrapper">
    <div>Extra Infomation </div>
    <div class="main_content">
        <p>here you can learn about me and my adventures</p>
    </div>
</div>
<div class="below_content">
    This is content below the main content
</div>

所以如果

它是一个类,在main_content之前放一个.,如果它是一个id,则放#

下面的 CSS 代码main_content ID 应该可以工作。

#main_content {
    width: 100%;
    height: 100px;
    position: absolute;
    bottom: 0;
    left: 0;
}

你可以试试在这里 https://jsfiddle.net/xsdr00dn/