user1996496 user1996496 - 2 months ago 6
CSS Question

How do I get a float left image and float right text aligned inside a box?

I am trying to create a box with an image on the left and text (title, price & description) aligned on the right. The problem is, the text is always displayed outside the box. What am I doing wrong here?

<div class="menu__item">
<div class="menu__item__photo"><img src="http://placehold.it/350x150" class="photo"></div>
<div class="menu__item__info__photo">

<div class="menu__item__info__title">Product Title Here</div>
<div class="menu__item__info__price">$9.99</div>

<div class="menu__item__info__description">Description here..</div>

</div>
</div>


And the CSS:

.photo{
width:100%
}
.menu__item{
width:100%;
border:1px solid #c4c4c4;
display:block;
}
.menu__item__photo{
width: 40%;
padding-right: 16px;
display:block;
}
.menu__item__info__photo{
width:60%;
display:block;
float:right;
}
.menu__item__info__title{
float:left;
width:78%;
}
.menu__item__info__price{
float:right;
width:21%;
text-align:right;
}


Here is a fiddle: https://jsfiddle.net/pxanzefe/

Answer

You can float your left item too:

  1. Float the .menu__item__photo item and add box-sizing to include the padding inside the 40% width.

  2. Use a clearfix method on your container.

.photo {
  width: 100%
}
.menu__item {
  width: 100%;
  border: 1px solid #c4c4c4;
  display: block;
}
.menu__item:after {
  content: "";
  display: table;
  clear: both;
}
.menu__item__photo {
  width: 40%;
  padding-right: 16px;
  display: block;
  float: left;
  box-sizing: border-box;
}
.menu__item__info__photo {
  width: 60%;
  display: block;
  float: right;
}
.menu__item__info__title {
  float: left;
  width: 78%;
}
.menu__item__info__price {
  float: right;
  width: 21%;
  text-align: right;
}
<div class="menu__item">
  <div class="menu__item__photo">
    <img src="http://placehold.it/350x150" class="photo">
  </div>
  <div class="menu__item__info__photo">
    <div class="menu__item__info__title">Product Title Here</div>
    <div class="menu__item__info__price">$9.99</div>
    <div class="menu__item__info__description">Description here..</div>
  </div>
</div>