Search code examples
csshtmlwidth

CSS Stretch to Available Width


How do I make a block-level element, such as a div stretch to the available width?

I know that this may seem like a question with an obvious answer, but it is a tad bit more complicated that it seems, have a look at this Fiddle:

http://jsfiddle.net/spryno724/pZKgv/

The CSS sets a left and right margin for the containing div to 20% on each side. Setting the width property causes it to stretch 100% of the original available space, causing it to spill off the side of the screen when the 20% margins are added to each side.

How can this be fixed, such that 20% margins still exist, but the div stretches to fill the remaining space in between?


Solution

  • This is what you had:

    .error {
      border: 1px solid black;
      display: inline-block;
      margin-left: 20%;
      margin-right: 20%;
      position: fixed;
      top: 0;
      width: 100%;
    }​
    

    Try this one:

    .error {
      border: 1px solid black;
      margin-left: 20%;
      margin-right: 20%;
      top: 0;
    }​