Set position absolute and margin

2019-01-11 16:37发布

I would like to set an element's position to absolute and have a margin-bottom, but it seems that the margin-bottom doesn't have an effect.

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
}

7条回答
对你真心纯属浪费
2楼-- · 2019-01-11 17:06

I have found the solution!!!

set a min-height of the container, the position will need to be changed from absolute to inherit, set the top property to a value of your choice and the display will need to be inline-block.

This worked for me when I tried using position absolute, moving the element with top property and try to add a margin.

min-height: 42px;
display: inline-block;
top: 6px;
position: inherit;
查看更多
小情绪 Triste *
3楼-- · 2019-01-11 17:12

For some use cases, changing position: absolute to position: relative solves this problem as well. If you can change your positioning, it will be the simplest way to solve the problem. Otherwise, the spacer of Joey does the trick.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-11 17:13

I know this isn't a very timely answer but there is a way to solve this. You could add a "spacer" element inside the element positioned absolutely with a negative bottom margin and a height that is the same size as the negative bottom margin.

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 */
}
查看更多
狗以群分
5楼-- · 2019-01-11 17:15

Since I don't know the height in advance, I instead added an invisible element at the end of the absolutely positioned with a height that I wanted the margin to be.

In my case, the absolutely positioned element is a table, so I added an extra empty row with a height of 100px. Then the border that was supposed to be at the bottom of the table went on "tr:nth-last-of-type(2) td" instead.

Hope this helps.

查看更多
孤傲高冷的网名
6楼-- · 2019-01-11 17:22

Building upon Joey's answer, for a cleaner markup, use the CSS :after-selector to add a spacer for the desired bottom margin.

CSS

#container:after {
    position: absolute;
    content: "";
    bottom: -40px;
    height: 40px;
    width: 1px;
}
查看更多
来,给爷笑一个
7楼-- · 2019-01-11 17:32

You need to set the position to relative in order to set its margin.

The margin-bottom, margin-left and margin-right will NOT work when the element is in position: absolute.

Example: HTML:

<img src="whatever.png"/>

CSS:

img {
   position: relative;
   margin: 0 auto;
}
查看更多
登录 后发表回答