how to stop overlapping of divs?

Viewed 59

when i set float to right for container this overlapping occurrs, what is reason for this how to avoid it? i want yellow div to below the red one and red one should be at right ...

.container {
    float: right;
    height: 150px;
    margin: 10px;
    width: 50%;
    display: flex;
    flex-direction: row;
    /* flex-wrap: wrap; */
    justify-content: center;
    align-items: center;
    background-color: yellow;
}
<div class="container"></div>
<div style="display: block; margin: auto; background-color: red; height: 200px; width: 100%;"></div>

enter image description here

2 Answers

Use rule clear: both for red div.

This is a keyword indicating that the element is floated down to clear both left and right floats.

.container {
    float: right;
    height: 150px;
    margin: 10px;
    width: 50%;
    display: flex;
    flex-direction: row;
    /* flex-wrap: wrap; */
    justify-content: center;
    align-items: center;
    background-color: yellow;
}
<div class="container"></div>
<div style="display: block; margin: auto; background-color: red; height: 200px; width: 100%; clear: both;"></div>

There are a few things wrong with this that I would like to point out.

  1. div element is by default a block element so no need to specify display: block;
  2. You are using display: flex and float:right on the same div you can use either of those.
  3. If you want to give float:right you should specify float:right on the other div as well or use clear: both on the red div to get it into the normal flow.
Related