Cody Ma Cody Ma - 9 months ago 40
CSS Question

Relative and absolute positioning confusion

I'm new to html/css and I've just started wrapping my head around positioning but I seem to have a misunderstanding. Right now I'm trying to create a page header with a horizontal divider right below it. My header is positioned absolutely, with a top and left value of 0, and a height of 88. I thought that if I gave my horizontal divider position: relative, and a height of 5, it would end up right below my header. Instead, it's ending up at the very top of the page, and I'm confused as to why.

I would like to use this horizontal divider again on my page, right above my footer, so I don't want to give this horizontal divider

position: absolute
top: 88px
. Any help is appreciated, thanks so much!

My (very simple) code so far:

<div id="header"></div>
<div class="horizontal-divider"></div>

#header {
position: absolute;
top: 0px;
left: 0px;
height: 88px;
width: 100%;

.horizontal-divider {
position: relative;
height: 5px;
width: 100%;
top: 0px;
background-color: white;
border: 1px solid black;

Answer Source

Absolute positioning positions an element with respect to the edges of its containing block. Its containing block is its closest ancestor that has position set to anything that isn't static. It also takes the element out of normal flow, so it doesn't influence the position of anything that follows it.

Relative positioning positions an element with respect to where it would be positioned if it was position: static (not with respect to any other element).

Since #header is absolutely positioned, .horizontal-divider is not positioned after it.

If you want an element to be rendered immediately after an absolutely positioned element, then:

  1. Don't absolutely position the first element
  2. Place both elements in another (container) element (so they are laid out one after the other in normal flow)
  3. Absolutely position the container element

That said, you should be able to get the effect you are after by setting border-bottom on the header and removing the divider entirely.