Elliot Alderson
Elliot Alderson

Reputation: 285

Bottom property on a relative child with a fixed parent doesn't work

I have a child element that have position:relative ; bottom: 0; and a parent div that have position: fixed ; height: 100vh;. The child element doesn't go to the bottom, why? Below you have the fullcode. With the inspector, I see the .secondary shape on the top, instead to be on the bottom.

HTML

<div class="fullpagenav active_nav">
  <div id="secondary" class="secondary toggled-on" aria-expanded="true">
  ...
  </div>
</div>

CSS

.fullpagenav {

    position: fixed;
    height: 100vh;
    width: 100%;
    z-index: 2;

}

.secondary.toggled-on {

    width: 100%;
    display: block;
    bottom: 0;
    position: relative;

}

menu-on-the-top

Upvotes: 2

Views: 352

Answers (4)

Nenad Vracar
Nenad Vracar

Reputation: 122145

That is not how position: relative works. It doesn't position elements relative to parent which you are trying to do here when you set bottom: 0, and you want that element to be at bottom of parent. That is what position: absolute is for but it will take that element out of normal elements flow. So other option is to use display: flex on parent element and align-self: flex-end on child element.

body, html {
  margin: 0;
}
.fullpagenav {
  position: fixed;
  height: 100vh;
  width: 100%;
  z-index: 2;
  background: gray;
  display: flex;
}

.secondary.toggled-on {
  width: 100%;
  background: black;
  color: white;
  align-self: flex-end;
}
<div class="fullpagenav active_nav">
  <div id="secondary" class="secondary toggled-on" aria-expanded="true">
   Div
  </div>
</div>

Upvotes: 0

Michał Sadowski
Michał Sadowski

Reputation: 2155

Bottom on relatively positioned elements means how far you want to move its bottom from the automatic position. In your case, 0, which makes it stay where it wants. You need either position: absolute or a flexbox:

.fullpagenav {
  display: flex;
  flex-direction: colum;
}

.secondary.toggled-on{
  margin-top: auto;
}

Upvotes: 0

Zeshan Tariq
Zeshan Tariq

Reputation: 41

There can be two solutions by using CSS properties

(i) vertical-align: bottom;

(ii) add position : relative to parent and position : absolute to child

Upvotes: 0

SpoonMeiser
SpoonMeiser

Reputation: 20467

position: relative positions an element relative to where it would normally be placed.

That is bottom: 0 says don't offset the element from where it would normally be placed.

What you're looking for is position: absolute

See the description of different position values here: https://developer.mozilla.org/en/docs/Web/CSS/position

In particular, it says this about relative (emphasis mine):

This keyword lays out all elements as though the element were not positioned, and then adjusts the element's position, without changing layout (and thus leaving a gap for the element where it would have been had it not been positioned).

Upvotes: 1

Related Questions