Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

width

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.

like image 391
Pinkie Avatar asked Oct 30 '11 22:10

Pinkie


People also ask

How do I change the width to 100% in CSS?

It seems like this should be one of the easiest things to understand in CSS. If you want a block-level element to fill any remaining space inside of its parent, then it's simple — just add width: 100% in your CSS declaration for that element, and your problem is solved.

How do I make my div wider than my parents?

- First set the width of the extended-content-container div to 500%. This will make the div you are trying to extend 5 time wider than the center column it lives inside. This can be adjusted up or down depending on the size of the center column you are working with.

Is a div 100% width by default?

auto automatically computes the width such that the total width of the div fits the parent, but setting 100% will force the content alone to 100%, meaning the padding etc. will stick out of the div, making it larger than the parent. so setting the 'width' to 'auto' would be better? Yes, but that's the default anyway.

How do you make a div 100 width?

The width property is used to fill a div remaining horizontal space using CSS. By setting the width to 100% it takes the whole width available of its parent. Example 1: This example use width property to fill the horizontal space. It set width to 100% to fill it completely.


2 Answers

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.
like image 108
Hussein Avatar answered Sep 23 '22 20:09

Hussein


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>
like image 23
Ian Dunn Avatar answered Sep 24 '22 20:09

Ian Dunn