简体   繁体   中英

How to make a div fill up remaining horizontal space

I have two divs. One that is floated left and one floated right. The one of the left has a width set to 18% and a min-width of 217px. I want to have the div on the right take up the remaining space, while also being able to resize to fit the window.

The problem I am having is that I can set the right div's width to 82% and to float right, which works until I make the window side too small, in which case the min-width of the left div kicks in and it stops shrinking. The right div doesn't have enough space to fit, so it is pushed down.

Here's some sample code.

HTML

    <div id="div1">
       stuff inside of it
    </div>
    <div id="div2">
       stuff inside of it
    </div>

CSS

    #div1
    {
     float: left;
     width: 18%;
     height: 100vh;
     min-width: 130px;
     box-shadow: 0px .3em .2em #000;
     z-index: 2;
    }

    #div2
    {
     width: 82%;
     float: right;
     z-index: 1;
    }

So this is where I'm stuck, how should I approach fixing div2? I've tried using a table instead of divs, but a border appeared around the cells that I couldn't change and it removed my box-shadow, so I would prefer a solution without it.

Your thinking of using tables is somewhat on the right track, as table elements do actually have many properties that make them capable of such a thing, but as people are pointing out in the comments, it's no longer a valid approach to use table elements for the purposes of layout for non-tabular data.

This is why CSS implemented a set of style rules built to reflect those unique properties. You can set a container around two elements with the style display: table; , and then give it's children the style display: table-cell;

Setting the width for the right side div to 100% will ensure it always fills as much space as is available to it.

But, since table cells can't break to a new row when the content exceeds the width of the table, it will automatically adjust to fit. So when another div (the left one) has a specific min-width, the div on the right is given less space in order to keep the cells contained.

Here's an example using your code:

http://jsfiddle.net/Q5rjL/

CSS table display properties give you all the benefits of these unique elements, but without the semantic issues. They are great for complex layouts where other style display types fall short.

You can also contain floats with overflow:hidden :

#div2{
  overflow:hidden;
  z-index: 1;
}

The DIV will fill up the remaining space ( http://jsfiddle.net/MAjwt/ )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM