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
}
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.
For some use cases, changing
position: absolute
toposition: 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.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
absolute
ly with a negative bottom margin and a height that is the same size as the negative bottom margin.HTML:
CSS:
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.
Building upon Joey's answer, for a cleaner markup, use the CSS
:after
-selector to add a spacer for the desired bottom margin.CSS
You need to set the
position
torelative
in order to set itsmargin
.The
margin-bottom
,margin-left
andmargin-right
will NOT work when the element is inposition: absolute
.Example: HTML:
CSS: