cpprookie
cpprookie

Reputation: 122

Child position absolute parent relative doesn't work

I’m trying to implement something like a web page navbar. I have code like this:

nav {
  position: relative;
  display: inline-block;
}

.nav-right {
  display: inline-block;
  position: absolute;
  right: 0px;
  list-style: none;
}
<nav>
  <h2>My First Website</h2>
  <ul class="nav-right">
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</nav>

I have known that an absolute element is positioned to its first positioned (not static) ancestor element. I have set position property of element nav as absolute, but it looks like the <ul> run out of the <nav> range. In other word i'm confused about why nav'height is less than ul's Thanks a lot.

enter image description here

Upvotes: 2

Views: 4456

Answers (4)

Ehsan
Ehsan

Reputation: 12951

Try This :

nav {
  position: relative;
}

.nav-right {
  display: inline-block;
  position: absolute;
  top: 0px;
  right: 0px;
  list-style: none;
} 
 <nav>
  <h2>My First Website</h2>
  <ul class="nav-right">
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</nav> 

Upvotes: 1

XYZ
XYZ

Reputation: 4480

try top : 0px; also with that.If the top is auto then it defaults to their position: static values.Check this for more details:position: absolute without setting top/left/bottom/right?

Also display:block for the nav for the nav to take full sapce

nav {
  position: relative;
  display: block;
}

.nav-right {
  display: inline-block;
  position: absolute;
  top:0px;
  right:0px;
  list-style: none;
}
<nav>
      <h2>My First Website</h2>
      <ul class="nav-right">
        <li>Home</li>
        <li>About</li>
        <li>Contact</li>
      </ul>
    </nav>

Upvotes: 1

jafarbtech
jafarbtech

Reputation: 7015

Use display: block; in parent and add top:0; in child to align in right side of parent

nav {
  position: relative;
  display: block;
}

.nav-right {
  display: inline-block;
  position: absolute;
  right: 0px;
  top:0;
  list-style: none;
}
<nav>
  <h2>My First Website</h2>
  <ul class="nav-right">
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</nav>

Upvotes: 1

karthick
karthick

Reputation: 12176

Absolute position elements are removed from the document flow. So the parent's height will hold only the other elements. Not the absolute position elements.

If you want your parent to cover your absolute position element then you have to set a fixed height to the parent element. You can set top: 0; like other's have answered. But still your parent's height wont be determined by the absolute positioned element, that's the reason the ul is outside the nav.

Upvotes: 2

Related Questions