Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot make DIV width 100% with scrollbar

Tags:

html

css

I have a page with a DIV and a TABLE. The DIV is my header and I want it to be 100% width even when horizontal scroll-bar displayed. For some reason it takes only 100% of visible window.

My HTML code is:

<!DOCTYPE html>
<html lang="en">
<body>

    <div style="background-color:yellow;">100% DIV</div>

    <table style="width:100%; background-color:orange;">
        <thead>
            <tr>
                <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_1</th>
                <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_2</th>
                <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_3</th>
            </tr>
        </thead>
    </table>

</body>
</html>

When I scroll to the right the DIV does not use all the width:

How can I make the DIV to take 100% of the page width? Ideally I do not want to change the TABLE because it's a generated code.

like image 608
Vad Avatar asked Nov 24 '15 22:11

Vad


1 Answers

There is no way (perfectly dynamically--without fixing any widths--and with pure CSS--no JavaScript) to get a block-level element to inherit the width of a sibling block-level element via a block-level parent element.

The workaround is to put display: inline-block on the parent element, since an inline-block calculates its width property from its widest child.

In your case, don't put display: inline-block on the body element. I would suggest wrapping your 100% div and table elements in another wrapper element, thus:

<!DOCTYPE html>
<html lang="en">
<body>
  <div class="wrapper" style="display: inline-block; min-width: 100%;">
    <div style="background-color:yellow;">100% DIV</div>
    <table style="width:100%; background-color:orange;">
      <thead>
        <tr>
          <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_1</th>
          <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_2</th>
          <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_3</th>
        </tr>
      </thead>
    </table>
  </div>
</body>
</html>

Also, putting min-width: 100% on the wrapper element will make it mimic an element with display: block on larger screen sizes.

like image 198
bowheart Avatar answered Oct 07 '22 13:10

bowheart