HTML Div Side by Side
In HTML, <div>
is a block-level element that is commonly used to group and style content. Sometimes, you may want to display multiple <div>
elements side by side on a webpage. In this article, we will discuss how to achieve this by using various methods in HTML and CSS.
Method 1: Using CSS Float Property
One of the most common ways to display <div>
elements side by side is by using the CSS float property. You can float the <div>
elements to the left or right to make them sit next to each other.
<!DOCTYPE html>
<html>
<head>
<style>
.left {
float: left;
width: 50%;
}
.right {
float: left;
width: 50%;
}
</style>
</head>
<body>
<div class="left">
<p>Left content goes here.</p>
</div>
<div class="right">
<p>Right content goes here.</p>
</div>
</body>
</html>
Output:
Method 2: Using CSS Flexbox
Another modern approach to achieve a side-by-side layout is by using CSS flexbox. Flexbox provides a more flexible way to layout items in a container, allowing for easier alignment and sizing of elements.
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: flex;
}
.item {
flex: 1;
}
</style>
</head>
<body>
<div class="container">
<div class="item">
<p>Item 1</p>
</div>
<div class="item">
<p>Item 2</p>
</div>
</div>
</body>
</html>
Output:
Method 3: Using CSS Grid
CSS grid is another powerful tool for creating complex layouts on a webpage. With CSS grid, you can easily create multiple columns and rows to position <div>
elements side by side.
<!DOCTYPE html>
<html>
<head>
<style>
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
}
</style>
</head>
<body>
<div class="grid">
<div>Grid item 1</div>
<div>Grid item 2</div>
</div>
</body>
</html>
Output:
Method 4: Using Bootstrap Grid System
If you prefer using a framework like Bootstrap, you can take advantage of its grid system to easily create responsive layouts with <div>
elements placed side by side.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm">
<p>Column 1</p>
</div>
<div class="col-sm">
<p>Column 2</p>
</div>
</div>
</div>
</body>
</html>
Output:
Conclusion
In conclusion, there are several methods to display <div>
elements side by side on a webpage using HTML and CSS. You can choose the method that best suits your needs depending on the layout complexity and design requirements of your project. Experiment with these methods and see which one works best for your specific use case.