IseNgaRt
IseNgaRt

Reputation: 609

inherit width doesn't work with percentage value

I have 2 divs. The parent div has relative position and the child div has fixed position.

If I use a flat amount of width on the parent div, width: inherit; works perfectly. When I use width: 100%; on the parent div, child div has more width than its parent.

*,
*::before,
*::after {
  box-sizing: border-box;
}
.content {
  position: relative;
  background: black;
  width: 100%;
}
.fixedElement {
  position: fixed;
  width: inherit;
  background: yellow;
  z-index: 2;
  top: 0px;
}
<div class="content">
  parent
  <div class="fixedElement">
    child
  </div>
</div>

Fiddle

Am I missing something here?

I'm thinking of using jQuery to set the width of the child but I'm sure it's not a good solution as it could be solved only with css.

Upvotes: 4

Views: 1620

Answers (3)

Rovi
Rovi

Reputation: 259

if you want the child element to inherit the width of the parent then it should be position absolute rather than fixed.

Upvotes: 0

Andrew
Andrew

Reputation: 1534

Because you are using position: fixed and top: 0 child div is overlapping your parent. If you need your child div be with position: fixed and you want to see the whole parent element, try to add also position: fixed to your parent and add some top value. This will show your parent elemtn under child element.

Or another solution could be is to change places for parent and child elements and use display: inline-block for both of them

Upvotes: 0

Hans
Hans

Reputation: 497

The body has a default margin. So the parent element will fill the entire width but will be limited due to that margin. The fixed element is not bound to the body and is the full width regardless of the margin.

However, it sticks out to the right of the parent because it is in the parent which has a position: relative. If you add a CSS rule like

body {
    margin: 0;
}

parent and child will be the same size.

Upvotes: 4

Related Questions