Width 100% May Not Be Your Friend

An example showing that sometimes placing 100% width on an interior block element may create layout problems.

by Travis Almand

HTML

<p>Both the inner and outer boxes have a padding of 10px.</p>

<div id='outer'><div id='inner'>100%</div></div>

<p>If the inner box has a width of 100%, it will break out of the the outer box. Changing the width to auto keeps it inside the outer box.</p>

<p>Click the button to toggle the class that changes the interior box's width property from 100% to auto.</p>

<button id='auto'>auto</button>

<p>Using border-box for box-sizing prevents this as well.</p>

<button id='box'>box sizing</button>

CSS

button {
    padding: 10px 20px;
}

#outer {
    border: 1px solid black;
    height: 200px;
    padding: 10px;
    width: 50%;
}

#inner {
    background-color: gainsboro;
    padding: 10px;
    width: 100%;
}
#inner.auto {
    width: auto;
}
.box {
    box-sizing: border-box;
}

JavaScript

$('#auto').on('click', function () {
    $('#inner').removeClass('box');
    $('#inner').toggleClass('auto');
    
    if ($('#inner').hasClass('auto')) {
        $('#inner').text('auto');
    } else {
        $('#inner').text('100%');
    }
});

$('#box').on('click', function () {
    $('#inner').removeClass('auto');
    $('#inner').toggleClass('box');
    
    if ($('#inner').hasClass('box')) {
        $('#inner').text('box-sizing');
    } else {
        $('#inner').text('100%');
    }
});