DEV Community

MD ASHRAF
MD ASHRAF

Posted on

Display HTML DIVs/Block elements side by side

As a beginner the difficult thing to design in a page is to put 2 div side by side, and that is the place where we make mistake and try achieving this by the ways which will make our page works in some browser/platform while it will look broken in other browsers.

Important is to design pages by using best practices. Todays here we will see all those possible ways to get it done.

Side by Side div image

Possible ways are as follows:

  1. Using CSS float property
  2. b. Using CSS flex-box
  3. c. Using CSS table properties
  4. d. Using CSS grid property(not explained in this post)

1. USING CSS FLOAT PROPERTY
In this approach, we will make both the div to float, i.e. div will acquire only the width specified or upto their content.

<div class=”parent-div”>
<div class=”div-1”>Div 1</div>
<div class=”div-2”>Div 2</div>
</div>
Enter fullscreen mode Exit fullscreen mode

Style.css

.div-1, .div-2 { float: left}
.div-1 {width: 40%}
.div-2 {width: 60%}
Enter fullscreen mode Exit fullscreen mode

** total viewport width is always 100%.

2. USING CSS FLEX-BOX
In this approach we will make parent div as display: flex, so that all the child div will by default come in a single row. This is the most used and suggested approach if you are going to make your webpage responsive(RWD) development

<div class=”parent-div”>
<div class=”div-1”>Div 1</div>
<div class=”div-2”>Div 2</div>
</div>
Enter fullscreen mode Exit fullscreen mode

Style.css

.parent-div {display: flex; flex-direction: row;} // (here flex-direction is optional as by default it arranges child in a row only)
.div-1 {width: 40% or flex-basis: 40%;}
.div-2 {width: 60% or flex-basis: 50%;}
Enter fullscreen mode Exit fullscreen mode

**For alignment please read CSS flex-box.

3. USING CSS TABLE PROPERTIES
In this approach we use css table properties, so that the div will align as a column inside each table row. This approach is not much used

<div class=”table-section”>
<div class=”table-row”>
<div class=”table-cell cell-1”>Div 1</div>
<div class=”table-cell cell-2”>Div 2</div>
</div>
</div>
Enter fullscreen mode Exit fullscreen mode

Style.css

.table-section {display: table; width: 100%} // width of the table in the page
.table-row {display: table-row;}
.table-cell {display: table-cell;}
.cell-1 {width: 40%}
.cell-2 {width: 60%}
Enter fullscreen mode Exit fullscreen mode

Thank you for reading this tutorial.

Please let me know your query or any other topics you want to understand in HTML5, CSS, SCSS, BOOTSTRAP, ANGULAR, CORDOVA etc.

Top comments (0)