JonX JonX - 5 months ago 7
CSS Question

Float element goes into the next box

When I add float to the first element, it just goes inside the second block. What's the reason for this?

Check the fiddle here:
https://jsfiddle.net/peterzhong/33m7k5gy/9/



.container {
position:relative;
width:10em;
height:10em;
background:#aaa;
float:left;
}
.positioned {
position:absolute;
top:50%;
left:50%;
bottom:0;
right:0;
background:#FFA500;
}
.container1 {
position:relative;
width:10em;
height:10em;
background:#0092ff;
margin-top:100px;
}
.positioned1 {
position:absolute;
top:75%;
left:75%;
bottom:-3em;
right:-3em;
background:#FFA500;
}

<div class="container">
box1
<div class="positioned"></div>
</div>
<div class="container1">
box2
<div class="positioned1"></div>
</div>




Answer

Based on your goal you have two different solutions here:

  1. If you are willing to separate the two containers in different lines, you need to add clear: both property to <div class="container1"> so it won't attach form left or right to any floating content.

.container {
  position:relative;
  width:10em;
  height:10em;
  background:#aaa;
  float:left;
}
.positioned {
  position:absolute;
  top:50%;
  left:50%;
  bottom:0;
  right:0;
  background:#FFA500; 
}
.container1 {
  position:relative;
  width:10em;
  height:10em;
  background:#0092ff;
  margin-top:100px;
  clear: both; /*Add this property*/
}
.positioned1 {
  position:absolute;
  top:75%;
  left:75%;
  bottom:-3em;
  right:-3em;
  background:#FFA500; 
}
<div class="container">
   box1
   <div class="positioned"></div>
</div>
<div class="container1">
  box2
  <div class="positioned1"></div>
</div>

  1. If you are willing to put both containers on the same line but NOT over each other, you will need to give <div class="container1"> a float property too.

.container {
  position:relative;
  width:10em;
  height:10em;
  background:#aaa;
  float:left;
}
.positioned {
  position:absolute;
  top:50%;
  left:50%;
  bottom:0;
  right:0;
  background:#FFA500; 
}
.container1 {
  position:relative;
  width:10em;
  height:10em;
  background:#0092ff;
  /*margin-top:100px;*/ /* Margin top removed to give both containers same height */
  float: left; /* Add this property */
}
.positioned1 {
  position:absolute;
  top:75%;
  left:75%;
  bottom:-3em;
  right:-3em;
  background:#FFA500; 
}
<div class="container">
   box1
   <div class="positioned"></div>
</div>
<div class="container1">
  box2
  <div class="positioned1"></div>
</div>

Comments