htmlcsscss-floatvertical-alignmenthorizontal-alignment

How can I vertically align a floated image


When I try to vertically align text on the left to the vertical middle of the image on the right, nothing works.

HTML

<div class= "div"> <p class= "alignleft">text on the left</p> <img src= "example.jpeg" class= 'alignright'> </div>

CSS

`.div {
align-tiems: center;

}

.alignleft {
  float: left;
}

.alignright {
  text-align: right;
  vertical-align: middle;
}`

This is what I've got so far. I have no clue how to move further

What I've got

              _______
             |       |
text on the left (image right next to it)

What I would like

                    ______
                   |      |
text on the left (image on far right)

Solution

  • Flexbox is the way to go here. howtocenterincss.com is a handy online tool to use to give you code to solve most problems. It can be very frustrating aligning text, images and other elements, that's for sure.

    .container {
      display: flex;
      align-items: center;
      /* This maximises the space between eleemnts */
      justify-content:space-between;
      
      /* you can use gap if you just want a fixed width between items */
      /* gap: 1rem */
      
    }
    <div class='container'>
      <div>Some Text here</div>
      <div><img src='https://www.fillmurray.com/200/100'>
      </div>
    </div>
    Edit changed to justify-content:space-between as that more closely matches the question meaning.