EN
How to align 2 div tags into left and right without using float?
2 answers
6 points
I always use float: left and float: right to solve this problem.
Is there a way to solve this in another way?
My code:
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
.div-left { border: 2px solid grey; margin: 15px; padding: 15px; }
6
.div-right { border: 2px solid grey; margin: 15px; padding: 15px; }
7
</style>
8
</head>
9
<body>
10
<div class="div-left" >Hello 1</div>
11
<div class="div-right">Hello 2</div>
12
</body>
13
</html>
This code produce:
How can I get div 1 to left and div 2 to right without using floats?
Example what I want to achieve:
2 answers
8 points
The best solutions is to use flex.
Put those 2 div's into another div and add to this outer div display flex and justify-content, like this:
xxxxxxxxxx
1
<div style="display: flex; justify-content: space-between;">
Full working example:
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
.div-left { border: 2px solid grey; margin: 15px; padding: 15px; }
6
.div-right { border: 2px solid grey; margin: 15px; padding: 15px; }
7
</style>
8
</head>
9
<body>
10
<div style="display: flex; justify-content: space-between;">
11
<div class="div-left" >Hello 1</div>
12
<div class="div-right">Hello 2</div>
13
</div>
14
</body>
15
</html>
If we want to have width of those divs like on your desired example, add width: 100%
to both divs.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
.div-left { border: 2px solid grey; margin: 15px; padding: 15px; width: 100%; }
6
.div-right { border: 2px solid grey; margin: 15px; padding: 15px; width: 100%; }
7
</style>
8
</head>
9
<body>
10
<div style="display: flex; justify-content: space-between;">
11
<div class="div-left" >Hello 1</div>
12
<div class="div-right">Hello 2</div>
13
</div>
14
</body>
15
</html>
Note, both classes are the same so we can use only one of them and remove second one. But I understand it is only for better picturing the problem.
0 commentsShow commentsAdd comment
7 points
Use display: inline-block
with width: calc(50% - 70px)
.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
.div-left {
6
margin: 15px;
7
padding: 15px;
8
border: 2px solid grey;
9
width: calc(50% - 70px);
10
display: inline-block;
11
}
12
.div-right {
13
margin: 15px;
14
padding: 15px;
15
border: 2px solid grey;
16
width: calc(50% - 70px);
17
display: inline-block;
18
}
19
</style>
20
</head>
21
<body>
22
<div class="div-left" >Hello 1</div>
23
<div class="div-right">Hello 2</div>
24
</body>
25
</html>
1 comments
5y
calc(...) is not supported by older browsers so I do not recommend this approach