Reputation: 2305
Continue make the browser smaller
<div id="container">
<div id="div1"><div class="content">one</div></div>
<div id="div2"><div class="content">two</div></div>
Why does div2 jump down a row instead of resizing? How can I solve this?
Upvotes: 2
Views: 1428
Reputation: 30408
When the divs are red, there are two relevant constraints that the divs try to follow: width: 48%
and margin-right: 10px
. If the div is jumping down a row instead of resizing, that means there isn’t enough space for both of them on that row – they are trying to take up more space than is available. Thus, the second div makes a new row for itself so both divs can be as wide as they want. So let’s look at the numbers and see why the divs are asking for too much space.
Load http://jsfiddle.net/roryokane/kZZCh/, which dynamically displays the width of the page and each div, and make the Result panel exactly 400px wide, so the bug shows itself. Now the two divs are 192px wide. That makes sense – 48% of 400px is 192px. The width does not include the margin, which is 10px for each div. So the total width the divs are asking for is (192+10)*2 = (202)*2 = 404 pixels, which is more than the 400px allotted to them. No wonder the divs are wrapping instead of staying on the same row.
So how do you solve this? Dany’s answer suggests changing the margin-right
value from a pixel value to a percent value. But that is only one possible solution. Finding the best solution depends on why you chose the two specific numbers in width: 48%
and margin-right: 10px
, and which number is more important to keep. If you need the width to remain at 48%
, consider whether you want to keep a fixed margin width or switch to a flexible margin width. If you you still want a fixed width, use margin-right: 8px
. If you want a flexible width, use margin-right: 2%
(Dany’s solution). On the other hand, if you need the right margin width to remain at 10px
, then for the width, use width: 47.5%
. All of these values ensure that even when the page is only 400px wide, the divs stay on the same row.
Upvotes: 0
Reputation: 765
You are adding margins for the smaller screen size. Set the margins to a percentage and subtract the percentage of the width for the smaller screen size.
So do not set a margin in pixels. but in percentages.
Upvotes: 4