Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align div elements next and under each other

Tags:

html

css

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?

like image 238
Tim Avatar asked Sep 02 '10 07:09

Tim


People also ask

How do I put two div elements next to each other?

With CSS properties, you can easily put two <div> next to each other in HTML. Use the CSS property float to achieve this. With that, add height:100px and set margin.

How do I align 3 divs next to each other?

Three or more different div can be put side-by-side using CSS. Use CSS property to set the height and width of div and use display property to place div in side-by-side format. float:left; This property is used for those elements(div) that will float on left side.

How do I put 4 divs next to each other?

you can use flex property for, Display:flex apply flex layout to the flex items or children of the container only. So, the container itself stays a block level element and thus takes up the entire width of the screen. ...


2 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;
}
like image 100
Yi Jiang Avatar answered Sep 21 '22 20:09

Yi Jiang


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>
like image 27
ArK Avatar answered Sep 21 '22 20:09

ArK