Align div elements next and under each other

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?

Answers


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 divs 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;
}

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>

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.


Need Your Help

rails http basic authentication

ruby-on-rails authentication

in the view file, how can i ,check whether the user is authenticated? is there any helper methods like signed_in?, logged_in? etc. ?

Android - Equivalent to Apache deprecated classes

java android json rest

I'm tring to find the equivalent of the code below because some classes are deprecated.