Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set position absolute and margin

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 } 
like image 411
kirby Avatar asked Feb 19 '12 16:02

kirby


People also ask

Does margin auto work with position absolute?

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.

How do you give margin to bottom absolute position?

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!

What is the absolute positioning?

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.

What is an example of absolute position?

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.


2 Answers

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 */ } 
like image 166
Joey Avatar answered Sep 28 '22 00:09

Joey


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; } 
like image 23
nik Avatar answered Sep 28 '22 01:09

nik