css - 设置绝对位置和 margin

标签 css position margin

我想将元素的 position 设置为 absolute 并有一个 margin-bottom,但似乎 margin -bottom 没有效果。

HTML:

<div id='container'></div>

CSS:

#container {
  border: 1px solid red;
  position: absolute; 
  top: 0px;
  right: 0px;
  width: 300px;
  margin-bottom: 50px; // this line isn't working
}

最佳答案

我知道这不是一个非常及时的答案,但有一种方法可以解决这个问题。您可以在 absolutely 定位的元素内添加一个“spacer”元素,该元素具有负底边距和与负底边距大小相同的高度。

HTML:

<div id="container">
    <div class="spacer"></div>
</div>

CSS:

// same container code, but you should remove the margin-bottom as it has no effect

// spacer code, made it a class as you may need to use it often
.spacer {
    height: 50px;
    margin: 0 0 -50px 0;
    /* margin: 20px 0 -50px 0; use this if you want #container to have a 'bottom padding', in this case of 20px */
    background: transparent; /* you'll need this if #container's parent element has a different background from #container itself */
}

关于css - 设置绝对位置和 margin ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9350775/

相关文章:

c++ - Qt QLabel setPixmap 不需要的填充

HTML5 列的内容从左到右

javascript - 移动设备上的溢出问题

html - 将部分的边缘隐藏在其他部分后面

html - 邮件客户端支持负 margin 值吗?

html - Chrome 9 中奇怪的边距错误

css - 用于字体信息的 Sass mixins

html - Google Gauge 设置字体大小和标签

css - 当最后一个图像或 div 从浏览器顶部到达指定点时如何锁定或修复滚动?

codeblocks - Code::Blocks - 如何在编辑器中显示装订线/垂直右边距线