在网页设计和开发中,有时候我们希望将一个元素始终保持在屏幕底部或内容底部,不管内容的高度如何变化。这种布局需求可以通过使用一些CSS技巧来实现。在本文中,我们将来实现这样的布局。
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
main {
width: 100%;
height: 100vh;
padding-bottom: 50px;
margin-bottom: -50px;
background: red;
padding: 10px;
}
section {
height: 300px;
background-color: yellow;
}
footer {
width: 100%;
height: 50px;
background: #000000;
}
</style>
</head>
<body>
<main>
<section></section>
</main>
<footer></footer>
</body>
使用padding属性和负的margin值
使用CSS的padding-bottom
属性结合负的margin-bottom
值来实现底部元素固定在屏幕底部。首先,将该元素的padding-bottom
属性设置为底部元素高度。接下来,设置负的margin-bottom
值来相应地将元素上移,使其位于屏幕底部。