Reputation: 733
i want to align 4 div boxes so that they are in a 2x2 layout like this
1 2
3 4
My code looks like this
<div style="width:300px;height:300px;float:left;"> DIV 1 </div>
<div style="width:300px;height:300px;float:left;"> DIV 2 </div>
<div style="width:300px;height:300px;clear:left;"> DIV 3 </div>
<div style="width:300px;height:300px;float:left;"> DIV 4 </div>
which produces the following layout:
1 2
3
4
Can someone help me with this?
Upvotes: 17
Views: 94213
Reputation: 50115
Give all of them float: left
, then wrap them in a container just wide enough to fit 2 of them, so that the other two gets pushed down. For example,
<div id="container">
<div>Div 1</div>
<div>Div 2</div>
<div>Div 3</div>
<div>Div 4</div>
</div>
CSS:
#container {
width: 600px;
}
#container div {
float: left;
height: 300px;
width: 300px;
}
Edit: If you want more div
s inside the ones you already got, then you can always apply the same technique to the children, like
<div id="container">
<div>
<div>Inner Div 1</div>
<div>Inner Div 2</div>
<div>Inner Div 3</div>
<div>Inner Div 4</div>
</div>
<div>Div 2</div>
<div>Div 3</div>
<div>Div 4</div>
</div>
Then with CSS, use this additional style:
#container div div {
float: left;
height: 150px;
width: 150px;
}
Upvotes: 27
Reputation: 43984
You can achieve it using this:
<body style="width:600px; height:600px;">
<div id="container">
<div style="width:50%; height:50%;float:left;">
DIV 1
</div>
<div style="width:50%; height:50%;float:left;">
DIV 2
</div>
<div style="width:50%; height:50%; float:left;">
DIV 3
</div>
<div style="width:50%; height:50%;float:left;">
DIV 4
</div>
</div>
</body>
Obviously by placing the style information in to a CSS file rather than in the HTML.
I would try to avoid setting the width & height to a specific size unless you simply cannot avoid it. It causes lots of issues when viewed on different browsers at different resolutions.
Upvotes: 1
Reputation: 21068
replace <div style="width:300px;height:300px;clear:left;">
of Div 3 with <div style="width:300px;height:300px; clear:both; float:left">
full html
<div style="width:300px;height:300px;float:left;">
DIV 1
</div>
<div style="width:300px;height:300px;float:left;">
DIV 2
</div>
<div style="width:300px;height:300px; clear:both; float:left">
DIV 3
</div>
<div style="width:300px;height:300px;float:left;">
DIV 4
</div>
Upvotes: 13