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 }
If the element is position absolutely, then it isn't relative, or in reference to any object - including the page itself. So margin: auto; can't decide where the middle is.
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. Or add a wrapper div with the padding. I tried both the main solution and the comment solution and they worked!
Absolute positioningElements that are relatively positioned remain in the normal flow of the document. In contrast, an element that is absolutely positioned is taken out of the flow; thus, other elements are positioned as if it did not exist.
Absolute-positioned elements are completely taken out of the regular flow of the web page. They are not positioned based on their usual place in the document flow, but based on the position of their ancestor. In the example above, the absolutely positioned square is inside a statically positioned parent.
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:
<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 */ }
Building upon Joey's answer, for a cleaner markup, use the CSS :after
-selector to add a spacer for the desired bottom margin.
#container:after { position: absolute; content: ""; bottom: -40px; height: 40px; width: 1px; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With