Damien Flury
Damien Flury

Reputation: 778

CSS: position element absolutely to absolute parent

I have a fixed navigation bar on the side of my page. I want to have a menu at the bottom of the nav-bar and inside that a button in form of an anchor-tag on the right side. So I used absolute positioning for the menu with bottom: 0. That works perfectly fine. But when I want to position the button absolute, the height of the menu is set to 0 and the button seems to be below the whole navbar.

HTML and CSS:

.fixed {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  width: 200px;
  border:solid;
}

.menu {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  border: solid;
}

.btn {
  position: absolute;
  right: 0;
  border: solid;
}
<div class="fixed">
  <div class="menu">
    <a class="btn">
        Hello
    </a>
  </div>
</div>

float: rightdidn't work either, with that approach the button is just still on the left side. How can I position the button on the right side of the menu?

Upvotes: 2

Views: 97

Answers (2)

Kaddath
Kaddath

Reputation: 6151

I see no reason why your button displays on the left with float:right, maybe there's another rule involved?

Also, because floating elements get out of the flow, you sould apply a clearfix if you want your .menu to adapt height to the link:

.fixed {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  width: 200px;
  border: 1px solid red;
}

.menu {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  border: 1px solid blue;
}

.btn {
  float: right;
  border: 1px solid green;
}

.clearfix::after {
    content: "";
    clear: both;
    display: table;
}
<div class="fixed">
  <div class="menu">
    <a class="btn">
        Hello
    </a>
    <div class="clearfix"></div>
  </div>
</div>

Upvotes: 0

Pete
Pete

Reputation: 58412

Why not just use text-align:right?

.fixed {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  width: 200px;
  border:solid;
}

.menu {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  border: solid;
  text-align:right;
}
<div class="fixed">
  <div class="menu">
    <a class="btn">
        Hello
    </a>
  </div>
</div>

Upvotes: 2

Related Questions