Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two 50% width divs don't fit in parent

Tags:

html

css

Sorry if it is a duplicate of something, I have searched honestly, but I still have the problem which is shown in this fiddle: http://jsfiddle.net/tfvdzzee/1/

The code here:

html

<div id="wrap">
    <div id="one">1</div>
    <div id="two">2</div>
</div>

css

#wrap
{
    max-width: 400px;
    margin: auto;
    border: 2px solid black;
}
#one, #two
{
    width: 50%;
    background: green;
}
#two
{
    float: right;
    background: red;
}
like image 597
VIRUS Avatar asked Aug 11 '14 13:08

VIRUS


3 Answers

I believe display: inline-block; is the best answer, as it prevents bugs of overlapping and overflowing, while also keeping its parent definitions.

JsFiddle Demo

HTML

<div id="wrap">
    <div id="one">1</div><!--
 --><div id="two">2</div>
</div>

CSS

#wrap
{
    max-width: 400px;
    margin: auto;
    border: 2px solid black;
}

#one, #two
{
    width: 50%;
    background: green;
    display: inline-block;
    /* If worried about IE7 and IE6, add the two next lines */
    *display: inline;
    *zoom: 1;
}

#two
{
    background: red;
}
like image 176
Sifu Avatar answered Nov 15 '22 21:11

Sifu


Demo Fiddle

You need to both float:left the #one element as well as set overflow:hidden to the parent to ensure it wraps the children correctly.

Change your CSS to:

#wrap
{
    max-width: 400px;
    margin: auto;
    border: 2px solid black;
    overflow:hidden; /* <---ensure the parent wraps the children */

}

#one, #two
{
    width: 50%;
    background: green;
    float:left; /* <---ensure the children display inline */
}

#two
{
    float: right;
    background: red;
}
like image 30
SW4 Avatar answered Nov 15 '22 19:11

SW4


Add the following style in your CSS.

 #one{float:left}

DEMO

like image 33
Suresh Ponnukalai Avatar answered Nov 15 '22 20:11

Suresh Ponnukalai