Search code examples
htmlcssflexboxcentering

Centering is thrown off by scrollbar width


I'm trying to center the content of two <div>s using flexbox. I have taken a look to the following thread: scrolling flex container does not fit centered items

The content of the <div>s is a table with fixed width and I set the flex-grow to none. The problem is that the space taken by the scrollbar of the second div is also considered while aligning.

Here a simple example: http://jsfiddle.net/boc39Lsa/2/

#container {
    background-color: green;
    display: flex;
    /*overflow: auto;*/
}
.item {
    background-color: white;
    border: 1px solid black;
    flex-grow: 0;
}


.item:first-child {
    margin-left: auto;
}
.item:last-child {
    margin-right:auto;
}

.bigContent{
  height: 1000px;
}

.scroll{
  overflow: auto;
  height: 300px;
}
<div id="container">
    <div class="item">
      <table width="500px">
        <tr><td>Header</td></tr>
      </table>
    </div>
</div>
<div id="container">
    <div class="item scroll">
      <div class="bigContent">
         <table width="500px">
            <tr><td>Some content</td></tr>
         </table>
      </div>      
    </div>
</div>


Solution

  • Since the scrollbar adds to an element's width, and as the width of a scrollbar differs between browsers, there is no immediate property to use to avoid this behavior.

    The simplest solution that cross my mind is to use an initial flex-basis of 500px and set the table to be 100% wide

    Stack snippet

    #container {
        background-color: green;
        display: flex;
    }
    .item {
        background-color: white;
        border: 1px solid black;
        flex-basis: 500px;
    }
    
    .item:first-child {
        margin-left: auto;
    }
    .item:last-child {
        margin-right:auto;
    }
    
    .bigContent{
      height: 1000px;
    }
    
    .scroll{
      overflow-y: auto;
      overflow-x: hidden;
      height: 300px;
    }
    <div id="container">
        <div class="item">
          <table width="100%">
            <tr><td>Header</td></tr>
          </table>
        </div>
    </div>
    <div id="container">
        <div class="item scroll">
          <div class="bigContent">
             <table width="100%">
                <tr><td>Some content</td></tr>
             </table>
          </div>      
        </div>
    </div>