position:absolute元素margin-bottom不生效 新增spacer div无效问题咨询
问题根源
设置了position: absolute的元素会脱离标准文档流,不会在正常排版中占据空间,因此你给它设置的margin-bottom、内部添加的spacer分隔元素,都只会作用于元素内部,不会对正常流中的.container-fluid产生任何挤压效果,这就是之前方案失效的核心原因。
解决方案
符合你给出的两个约束的前提下,最简单的实现方式是给<body>设置和顶部absolute元素高度匹配的padding-top,把正常流的整体内容向下挤,避开顶部的absolute元素,完全不会触碰.container-fluid的margin-top属性,也不需要修改position: absolute的配置。
修改后的代码示例
CSS部分
#container-test { position: absolute; background-color: #ffffff; top: 0; left: 0; width: 100%; height: 65px; } /* 新增body的padding-top,数值等于absolute元素高度 + 你需要的额外下方间距 */ body { padding-top: 65px; /* 如果需要额外10px间距就改成75px,按需调整 */ } /* 原spacer不会对外部元素产生作用,可直接删除 */
HTML部分
<head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <link rel="stylesheet" href="./example.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <!-- 把absolute顶部容器移到最前面,逻辑更顺,不影响功能 --> <div id='container-test'> <p>This text should have a margin-bottom to push the other elements down.</p> </div> <div class="container-fluid"> <h1>Hello World!</h1> <p>Resize the browser window to see the effect.</p> <p>The columns will automatically stack on top of each other when the screen is less than 768px wide.</p> <div class="row"> <div class="col-sm-4"> <h3>Title 1 - col-sm-4</h3> </div> <div class="col-sm-4" style="background-color:lavenderblush;"> <div class="section-topleft"> <h3>Title 1 - col-sm-4</h3> </div> <h3>Title 2 - col-sm-4</h3> </div> <div class="col-sm-4" style="background-color:lavender;"> <h3>Title 3 - col-sm-4</h3> </div> </div> </div> </body>
动态高度适配方案
如果顶部absolute元素高度是动态变化的,没法写死数值,可以用JS动态计算高度后赋值给body的padding-top:
// 页面加载完成后设置间距 window.onload = function() { const topBar = document.getElementById('container-test') const barHeight = topBar.offsetHeight // 如需额外间距,后面加对应的数值即可,比如 + 20 document.body.style.paddingTop = barHeight + 'px' } // 窗口大小变化时同步更新间距 window.onresize = function() { const topBar = document.getElementById('container-test') const barHeight = topBar.offsetHeight document.body.style.paddingTop = barHeight + 'px' }
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

