Merging all elements into a single line
To ensure that all div elements are in one line, wrap them inside a parent div:
<div id="wrapper">
<div id="first">first</div>
<div id="second">second</div>
<div id="third">third</div>
</div>
Next, adjust the wrapper width and float each div element:
#wrapper {
width:700px;
clear:both;
}
#first {
background-color:red;
width:200px;
float:left;
}
#second {
background-color:blue;
width:300px;
float:left;
}
#third {
background-color:#bada55;
width:200px;
float:left;
}
It is recommended to use IDs or classes for better organization and separation of CSS from HTML, making it easier to manage.
For achieving equal heights for all elements on the same line, utilize display:table
, display:table-row
, and display:table-cell
properties. An additional div will be used for this purpose:
<div id="wrapper">
<div id="row">
<div id="first">first</div>
<div id="second">second<br><br></div>
<div id="third">third</div>
</div>
</div>
The float property can be removed with the following CSS:
#wrapper {
display:table;
width:700px;
}
#row {
display:table-row;
}
#first {
display:table-cell;
background-color:red;
width:200px;
}
#second {
display:table-cell;
background-color:blue;
width:300px;
}
#third {
display:table-cell;
background-color:#bada55;
width:200px;
}
If targeting modern browsers (IE 10+), consider using Flexbox as an alternative method. Here's how you can implement it:
<div class="container">
<div class="first">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div>
<div class="second">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil ratione rerum deserunt reiciendis numquam fugit dolor eligendi fuga sit. Hic, tempore. Error, temporibus possimus deserunt quisquam rerum dolor quam natus.Fugiat nam recusandae doloribus culpa obcaecati facere eligendi consectetur cum eveniet quod et, eum, libero esse voluptates. Ut commodi consequuntur eligendi doloremque deserunt modi animi explicabo aperiam, non, quas qui!</div>
<div class="third">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet obcaecati, rem. Ullam quia quae, ad, unde saepe velit incidunt, aliquid eum facere obcaecati molestiae? Repellendus tempore magnam facere, sint similique!</div>
</div>
Utilize the following CSS to apply Flexbox layout:
.container {
display:flex;
justify-content:center;
}
.container > div {
margin:10px;
background-color:#bada55;
}
.first, .third {
width:200px;
}
.second {
width:300px;
}
If Grid layout is preferred, here's how to achieve it:
.container {
display:grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 1fr;
grid-column-gap: 10px;
width:700px;
}
.container > div {
background-color:#bada55;
}
.first, .third {
width:200px;
}
.second {
width:300px;
}