Aligning containers horizontallly

41 0 0 0

Last Updated : 2020-10-24 12:11:32

When designing a web page, alot of times you will need to put two or more divs or containers beside each other. The default behavior is that they will wrap under each other. in this snippet you will different methods to put them together without affecting other elements without intention.

In order to put elements or divs beside each other without warping on two or more lines, Yoiu can try one of the following methods:
But before we do this, let's assume that this the HTML code that contains a parent div and a three child divs.


<header>
<div class="first" style="background-color: yellow;">
ONE
</div>
<div class="second" style="background-color: red;">
TWO
</div>
<div class="third" style="background-color: lightcoral;">
THREE
</div>
</header>

<div style="background-color: lightblue;">
hehehhe
</div>


  • Using display: table, table-row and table-cell. (please note, that in this method we will increase a new div, so that we have divs representing table elements as table - row - cell)


<!-- HTML Code -->
<header>
<div class="row">
<div class="first" style="background-color: yellow;height: 100px;">
ONE
</div>
<div class="second" style="background-color: red;">
TWO
</div>
<div class="third" style="background-color: lightcoral;">
THREE
</div>
</div>
</header>

<!-- CSS code -->
header {
background-color: aqua;
display: table;
width: 100%;
}

header > div.row {
display: table-row;
}

header > div.row > div {
border : 2px solid red;
width : 33.333%;
content: 'hi';
display: table-cell;
}


  • Using float:left, or float:right


header{
border: 2px solid blue;
width:100%;
display: inline-block;
height: 100px;
}

header > div {
width: 30.333%;
float: left;
/* height: 100px; */
height: inherit;

}
header > div:last-child{
width: 30.333%;
float: right;
/* height: 100px; */
height: inherit;

}


  • Using Flexbox : display: flex and justify-content: center


div.row{
background-color: #336699;
display: flex;
justify-content: center;
}

.row > div {
margin: 2px;
border: 2px solid yellow;
vertical-align: middle;
/* height:100px; */
}

.left {
width: 20%;
background-color:red;
}
.center {
width:50%;
background-color: #999;
}
.right{
width:30%;
background-color: yellow;
}

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .