设置绝对位置和边距

时间:2012-02-19 16:08:53

标签: 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
}

8 个答案:

答案 0 :(得分:33)

我知道这不是一个非常及时的答案,但有办法解决这个问题。你可以添加一个&#34; spacer&#34;元素内部元素位于absolute,底部边距为负,高度与负底边距相同。

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 */
}

答案 1 :(得分:20)

Joey's answer的基础上,为了获得更清晰的标记,请使用CSS :after - 选择器为所需的底部边距添加间隔符。

CSS

#container:after {
    position: absolute;
    content: "";
    bottom: -40px;
    height: 40px;
    width: 1px;
}

答案 2 :(得分:15)

当您的元素位于其顶部时,您期望margin-bottom做什么?

如果元素没有margin-bottom属性,

absolute将只对top定位元素执行任何操作。

答案 3 :(得分:1)

您需要将position设置为relative才能设置其margin

margin-bottom margin-left margin-right 当元素位于 position: absolute 时工作。

实施例: HTML:

<img src="whatever.png"/>

CSS:

img {
   position: relative;
   margin: 0 auto;
}

答案 4 :(得分:0)

对于某些用例,将position: absolute更改为position: relative也可以解决此问题。如果您可以更改定位,这将是解决问题的最简单方法。否则,Joey的间隔就可以了。

答案 5 :(得分:0)

我找到了解决方案!!!

设置容器的最小高度,需要将位置从绝对更改为继承,将top属性设置为您选择的值,并且显示将需要内嵌块。

当我尝试使用绝对位置时,这对我有用,使用top属性移动元素并尝试添加边距。

min-height: 42px;
display: inline-block;
top: 6px;
position: inherit;

答案 6 :(得分:0)

由于我事先并不知道高度,所以我在绝对定位的末尾添加了一个不可见的元素,其高度为我想要的边距。

在我的情况下,绝对定位的元素是一个表,所以我添加了一个额外的空行,高度为100px。然后应该在表格底部的边界继续“tr:nth-​​last-of-type(2)td”。

希望这有帮助。

答案 7 :(得分:0)

我有一个绝对位置,需要在右边设置一个边距。 这是我想出的方式:

position:absolute;
  top:0px;
  left:10px;  
  width: calc(99% - 10px);
  height:80%;
相关问题