Width adjustment to take up space remaining to be occupied in a div

Asked

Viewed 4,123 times

1

Supposing I have this structure:

<div style="width:1000px">
    <div id="div1" style=""></div>
    <div id="div2" style="width:300px"></div>
</div>

How to make the div1 occupy exactly the remaining space (700px) ?

Preferably considering possible div1 and div2 margins.

At first I would like to do this with CSS only, but if there is no solution it can be via javascript/jquery.

NOTE: I cannot add extra html elements. Div2 has fixed width.

OBS2: The real scenario is a Table cell. In this cell I have the input field that would be "div1" in my example. And a little magnifying glass image on the side, which would be the fixed-size div2. I want these two elements to fit together to take up the entire space of the cell

  • If using % instead of px solves these problems

  • I added comments @Cesarmiguel

  • @Joaopaulo very likely you will have problem solving on unconventional screens (smartphones and others). The Bootstrap can help you solve this and other future problem. Depending on what you are doing, it is worth thinking about using it.

1 answer

5


First, you must allow the two Divs to occupy the same line. To do so use the display: inline-block. Then you need to remove the space between the Divs. Note the following:

<div id="div1">Conteúdo 1</div>
<div id="div2">Conteúdo 2</div>

There is a line break and spaces between </div> and <div>. Unfortunately they will make a difference in layout. HTML processing collapses multiple spaces into a single space, but it does not cease to exist. The character will be inserted between the two " ". Some separation pixels that will be visible. You can go around like this:

<div id="div1">Conteúdo 1
</div><div id="div2">Conteúdo 2
</div>

Ugly, but it works. Then apply the width either on the second div and on the first use the following:

width: calc(100% - 200px);

That is, the total size of the container less the size of the second div. Note that the space around the operator - is important, do not remove.

Final working example: http://jsfiddle.net/Ggzkb/

  • I didn’t understand what the line break problem was.

  • 1

    @Felipestoker improved the text

  • for you to see how this site is essential in the life of those who are starting, 2014 question helping me after 4 years, thanks @Guilherme

Browser other questions tagged

You are not signed in. Login or sign up in order to post.