Home > Back-end >  I need help positioning 3 elements, 2 with floats, but can't figure out why the unfloated eleme
I need help positioning 3 elements, 2 with floats, but can't figure out why the unfloated eleme

Time:05-12

I'm new to CSS and banging my head against a wall trying to figure out why when I have 2 elements floated right and one left that the third doesn't show up in the middle.

#red {
  width: 250px;
  height: 250px;
  background-color: red;
  float:left;
}

#yellow {
  width: 250px;
  height:250px;
  background-color: yellow;
  float:right;
 }


#blue {
  width: 250px;
  height:250x;
  background-color:blue;
}
<p id="red">This is bullshit.</p>

<p id="yellow">It is taking me way to long to figure out.</p>

<p id="blue">WTF?</p>

CodePudding user response:

I higly recomended to use flexbox for this issue.

.container {
  display: flex;
  justify-content: space-between;
}

   #red { width: 250px; height: 250px; background-color: red;  } 
   #yellow { width: 250px; height:250px; background-color: yellow; } 
   #blue { width: 250px; height:250x; background-color:blue; } 
<div >
  <p id="red">This is bullshit.</p>
  <p id="yellow">It is taking me way to long to figure out.</p>
  <p id="blue">WTF?</p>
</div>

CodePudding user response:

The problem arises because the third element is a p element which is not an inline element by default.

See MDN

The float CSS property places an element on the left or right side of its container, allowing text and inline elements to wrap around it.

Try setting blue to display: inline and you will see the difference.

If you genuinely need the red and yellow to float, that is, for the blue stuff to be in the middle and then wrap around, then obviously stick to float. If that is not required then investigate flex or grid.

CodePudding user response:

I also recommended you to use Flex Box Property, though if you wants to fix it with trinational way here is the solution for you:
First you have to understand that by default p tag is display block property so you have to make it as inline block, like span tag, and make the overflow hidden so it will not take any additional space.

#red,#yellow,#blue{
  display: inline-block;
  overflow: hidden;
}

#red {
  width: 150px;
  height: 150px;
  background-color: red;
  float: left;

}

#yellow {
  width: 150px;
  height:150px;
  background-color: yellow;
 }


#blue {
  width: 150px;
  height:150px;
  background-color: blue;
}
<p id="red">This is bullshit.</p>

<p id="yellow">It is taking me way to long to figure out.</p>

<p id="blue">WTF?</p>

  • Related