Program-Me-Rev
Program-Me-Rev

Reputation: 6634

How to make a div fill the parent element

Whenever I style a DIV to:

.div {
    position: fixed;
    z-index: 9999;
}

I start struggling with setting the div width to fit/ wrap the entire width of the parent element. If I set to width: 100%; stretches across the whole page. max-width, min-width all behave the same way. How can I resolve this so that a div elements fits perfectly across the parent element?

Upvotes: 0

Views: 152

Answers (2)

Carele
Carele

Reputation: 784

Try : position: relative; display: block on the parent element. .

Width % scale on the first ascendant WITH position: relative.

EDIT: As mentionned by @David Wilkinson this won't work with %width since they are set according to the window size. However, you might want to try : width: inherit (on the fixed bloc and any bloc between the set sized parent and the fixed bloc).

http://codepen.io/Carele/pen/ezBbwV Working here

Upvotes: 1

David Wilkinson
David Wilkinson

Reputation: 5118

Remember that when you declare an element as position: fixed, you're taking it out of the "normal" flow of a document - so don't expect normal rules to apply... Take this example:

.wrapper {
  width: 50%;
  background-color: red;
  height: 100px;
  margin: 0 auto;
}
.fixed {
  position: fixed;
  width: 100%;
  height: 50px;
  background: yellow;
  top: 0;
  left: 0;
}
<div class="wrapper">
  <div class="fixed">
    FIX ME!
  </div>
</div>

As you can see, even though the div with class fixed it still goes beyond the width of its parent element when I set its position to 100%...

To mimick what you're trying to do, try another approach with position: absolute on the child element and relative on the parent:

.wrapper {
  width: 50%;
  background-color: red;
  height: 100px;
  margin: 0 auto;
  position: relative;
}
.fixed {
  position: absolute;
  width: 100%;
  height: 50px;
  background: yellow;
  top: 0;
  left: 0;
}
<div class="wrapper">
  <div class="fixed">
    FIX ME!
  </div>
</div>

NOTE - you may need to add some top padding to the parent element so the child element doesn't overlap the parent's content... If you also want the child div to appear at the very top of the document, you'll also need to make sure the parent div is at the start of the document.

Upvotes: 1

Related Questions