Pinkie
Pinkie

Reputation: 10256

CSS make div 100% width relevant to body and not it's parent div

I have

<div style="position:relative; width:500px;">
    <div style="position:absolute; width:100%"></div>
</div>

The child div takes 100% width of it's parent div. Is there a way i can force it to take 100% width of body and not the parent div. Both relative and absolute positioning are required as i have it in the code above.

Upvotes: 9

Views: 8029

Answers (3)

LuckyLuke Skywalker
LuckyLuke Skywalker

Reputation: 791

Nowerdays you can make sth relative to the viewport via

viewport width vw

viewport height vh

whichever is larger vmax

whichever is smaller vmin

This may be an alternative for many.

In case anyone will ever stumble upon this thread again :)

Upvotes: 1

Ian Dunn
Ian Dunn

Reputation: 3680

Modern browsers have support for viewport units.

header {
    width: 50%;
    background-color: lightblue;
    padding: 20px 0;
}

nav {
    width: 100vw;
    background-color: orange;
    padding: 20px 0;
}
  <html>
  <body>
  
  <header>
    <p>This inherits the width of the parent like normal.</p>
    
    <nav>
      <a href="/">this fills the viewport</a>
    </nav>
  </header>
  
  </body>
  </html>

Upvotes: 4

Hussein
Hussein

Reputation: 42818

The only way to do this while keeping the relative and absolute positioning as you have in your code is to use JavaScript. You need to get window width and set that as the div width. You also need to detect window size on resize so you always have your div adjust set to the current window width.

The other 2 ways you can do this may not be options for but worth mentioning

  1. Put the child div outside the parent div.
  2. Or set it to fixed position. Doing this may not give a desirable effect. The div will always be in the same position regardless of page scroll.

Upvotes: 1

Related Questions