Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS Float issue Reply To: Float issue

#158248
Merri
Participant

Easy way to avoid floats rearranging as described is to only float the first element. The second element would then be a regular block that instead will get margin to the side where the floated element is at. So in your case you would have:

  • element 1, float: right; (calculate it’s width + padding + border + margin).
  • element 2, margin-right: #px (where # is the total size calculated based on above).
  • element 2 should have no width defined, so it uses container element’s width minus the size mentioned above.

This makes element 2 to not go on top of the floated element 1. Also because both aren’t floats there will be no elements clearing due to them being floated. We only do the margin stuff so that text content in element 2 does not expand to go below element 1, which would happen if element 2 is taller than element 1.

Alternatively:

.container {
  display: table;
  width: 100%;
}

.element1 {
  display: table-cell;
  width: 50%;
}

.element2 {
  display: table-cell;
  width: 50%;
}

There is nothing wrong in table based layout as long as you’re doing it in CSS. It is HTML tables for layout that are evil.