The cause of this is float
CSS attribute and as mentioned by the documentation:
The element is removed from the normal flow of the page, though still
remaining a part of the flow (in contrast to absolute positioning).
There are many ways to deal with this situation and fix the flow of items surrounding a floating element one of them mentioned by the documentation too in clear section:
Sometimes you may want to force an item to move below any floated
elements. For instance, you may want paragraphs to remain adjacent to
floats, but force headings to be on their own line. See clear for
examples.
div.a {
height: 200px;
width: 50%;
background-color: blue;
float: left;
}
div.b {
height: 200px;
width: 50%;
background-color: red;
clear: left;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="a">aa</div>
<div class="b">ccc</div>
</body>
</html>
also in your case you have to add floating right to your div.b
to fix the flow of .b
element in the page:
div.a {
height: 200px;
width: 50%;
background-color: blue;
float: left;
}
div.b {
height: 200px;
width: 50%;
background-color: red;
float: right;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="a">aa</div>
<div class="b">ccc</div>
</body>
</html>
another way to is add display:inline-block too:
div.a {
height: 200px;
width: 50%;
background-color: blue;
float: left;
}
div.b {
height: 200px;
width: 50%;
background-color: red;
display:inline-block;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="a">aa</div>
<div class="b">ccc</div>
</body>
</html>
and another example:
div.a {
height: 200px;
width: 50%;
background-color: blue;
float: left;
}
div.b {
height: 200px;
width: 50%;
background-color: red;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="a">aa</div>
<br />
<div class="b">ccc</div>
</body>
</html>