设置绝对位置和边距

kir*_*rby 30 css position margin

我想设置元素positionabsolute和有一个margin-bottom,但似乎margin-bottom没有效果.

HTML:

<div id='container'></div>
Run Code Online (Sandbox Code Playgroud)

CSS:

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

小智 39

我知道这不是一个非常及时的答案,但有一种方法可以解决这个问题.您可以在元素内部添加"spacer"元素absolute,其中底部边距为负,高度与负底边距相同.

HTML:

<div id="container">
    <div class="spacer"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

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 */
}
Run Code Online (Sandbox Code Playgroud)

  • 或者使用填充添加包装div. (3认同)

nik*_*nik 25

基于Joey的回答,为了获得更清晰的标记,请使用CSS :after-selector为所需的底部边距添加间隔.

CSS

#container:after {
    position: absolute;
    content: "";
    bottom: -40px;
    height: 40px;
    width: 1px;
}
Run Code Online (Sandbox Code Playgroud)


Nie*_*sol 16

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

margin-bottomabsolute如果元素没有top属性,它将只对ly-located元素执行任何操作.

  • 我在“容器”下面有与“容器”重叠的元素。如果margin-bottom起作用,则这些元素将向下移动。这些元素没有`position`属性 (2认同)
  • 不,你不能那样做。一旦元素具有“ position:absolute”,就好像它从未在流程中出现过。有点像在其上设置“ display:none”。要么在其中的“ #container”上放置“ padding-top”,要么使用“ position:relative”。 (2认同)

小智 6

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

当元素位于 中时,margin-bottom,和将不起作用margin-leftmargin-rightposition: absolute

示例:HTML:

<img src="whatever.png"/>
Run Code Online (Sandbox Code Playgroud)

CSS:

img {
   position: relative;
   margin: 0 auto;
}
Run Code Online (Sandbox Code Playgroud)