Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

I want to have 3 divs aligned inside a container div, something like this:

[[LEFT]       [CENTER]        [RIGHT]]

Container div is 100% wide (no set width), and center div should remain in the center after resizing the container.

So I set:

#container{width:100%;}

#left{float:left;width:100px;}

#right{float:right;width:100px;}

#center{margin:0 auto;width:100px;}

But it becomes:

[[LEFT]       [CENTER]              ]

                              [RIGHT]

Any tips?

2 Answers

0 votes
by (40.7k points)

In CSS, you can use the divs like so (floats first):

<div id="container">

  <div id="left"></div>

  <div id="right"></div>

  <div id="center"></div>

</div>

Note: You can also float right, then left, then center. The important thing is that the floats come before the "main" center section.You often want last inside #container this snippet: <div style="clear:both;"></div> which will extend #container vertically to contain both side loats instead of taking its height only from #center and possibly allowing the sides to protrude out the bottom.

0 votes
by (3.1k points)

To align three div elements (left, center, and right) inside a parent div, you can use CSS Grid. Here’s how to achieve it using css. 
<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>Align Divs</title> 
<style> 
.container { 
display: grid; 
grid-template-columns: 1fr auto 1fr; /* Left and right take available space */ 
width: 100%; /* Adjust width as needed */ 
border: 1px solid #ccc; /* Optional for visualization */ 
align-items: center; /* Center vertically if needed */ 
} 
.left, .center, .right { 
padding: 10px; /* Optional for spacing */ 
} 
.center { 
text-align: center; /* Center the text inside the center div */ 
} 
</style> 
</head> 
<body> 
<div class="container"> 
<div class="left">Left</div> 
<div class="center">Center</div> 
<div class="right">Right</div> 
</div> 
</body> 
</html> 

Related questions

0 votes
1 answer
0 votes
1 answer

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...