如何用CSS在headermenu头部下方设置间距
问题:头部菜单与下方表格无法设置间距
我无法在headermenu底部与列表顶部之间设置任何间距,设置margin-bottom或padding-bottom属性都无法让表格下移。我可以给表格添加margin-top,但由于该头部在全站复用,我更希望在头部处一次性解决,而非在每个页面做临时修复。
代码示例
CSS代码
#headermenu { position: absolute; padding: 0 0 50px 0; font-weight: normal; font-size: 75%; width: 100%; } .alignleft { float: left; } .alignright { float: right; } .tc { margin-left: auto; margin-right: auto; border: 1px solid black; }
HTML代码
<body> <div id="headermenu"> <div class="alignleft">Create New</div> <div class="alignright"><a href="?logout">Logout</a></div><br> <div style="clear: both;"></div> <div class="alignleft">View</div> <div class="alignright"><a href="?edituser">Manage User Settings</a></div> <div style="clear: both;"></div> <div class="alignleft"><a href="index.php">Main Menu</a></div> <div class="alignright"><a href="?admin">Administrator Options</a></div> <div style="clear: both;"></div> </div> <table border id="List" class="tc"></table> </body>
解决方案
问题核心在于#headermenu使用了position: absolute——绝对定位的元素会脱离正常文档流,不占据页面空间,因此它的padding-bottom或margin-bottom根本无法影响下方表格的位置。
方法一:改用相对定位(推荐)
将position: absolute替换为position: relative,让头部回到正常文档流中,此时设置的padding-bottom就能自动推开下方的表格,无需修改其他页面:
#headermenu { position: relative; /* 替换absolute */ padding: 0 0 50px 0; /* 这个padding-bottom现在会生效 */ font-weight: normal; font-size: 75%; width: 100%; }
方法二:保留绝对定位的替代方案
如果因布局需求必须保留position: absolute,可以给#headermenu添加一个伪元素来占据空间,从而推开下方表格:
#headermenu { position: absolute; padding: 0 0 50px 0; font-weight: normal; font-size: 75%; width: 100%; } /* 通过伪元素生成占位空间 */ #headermenu::after { content: ""; display: block; height: calc(100% + 50px); /* 头部高度 + 所需间距 */ }
注意:这种方法需要头部高度固定,否则伪元素的高度无法准确匹配头部实际高度。
内容的提问来源于stack exchange,提问作者Jake
相关产品推荐
相关产品推荐

