Search code examples
htmlcsscentering

How can I put my text and image in the middle of a div?


I have 4 different rows of two columns and I have a picture on one column and text on the other. As the text and images are different sized I want them to be in the middle vertically.

This is my code for one of the columns and CSS for that div

.col2 {
  float: left;
  width: 46%;
  padding: 2%;
  text-align: center;
  position: relative;
  justify-content: center;
  height: 300px;
}
<div class="col2">
        <img src="images/freelance.png" alt="three people watching a presentation">
</div>
<div class="col2">
    <h2>Work as a Freelancer</h2>
    <p>This session will set out the key points you need 
       to consider when taking on freelance work in order to make
       sure you gain maximum professional and personal benefit.</p>
    <div class="book">
        <a class="booked" href="#" target="_blank"><p><b>Book 14th March 6pm</b></p></a>
    </div>
</div>

This is the before with my code

This is with @N3v4da Stone 's changes


Solution

  • N3v4da's explanation does work, however I will try and go into some more detail.

    Wrapper div uses flexbox to display elements in a row.

    align-items: center; centers items vertically along the flex row (this means that the text is centered with the image)

    justify-content: space-between puts the img and div elements to opposite sides of the wrapper div.

    gap: 20px ensures there is always a 20px gap in between the img and div

    .wrapper {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 20px;
      
      background-color: lightblue;
    }
    
    .wrapper img {
      width: 300px;
      height: 300px;
    }
    <div class="wrapper">
    
      <img src="https://www.w3schools.com/w3css/img_lights.jpg" alt="three people watching a presentation">
    
      <div class="rightSide">
        <h2>Work as a Freelancer</h2>
        <p>This session will set out the key points you need to consider when taking on freelance work in order to make sure you gain maximum professional and personal benefit.</p>
        <div class="book">
          <a class="booked" href="#" target="_blank">
            <p><b>Book 14th March 6pm</b></p>
          </a>
        </div>
      </div>
    </div>

    Make sure you remove any CSS that may interfere with this code, this might be why N3v4da's version didn't work. This is what my solution does