Search code examples
htmlcsscss-floatmargin

Is a margin in css a proper way to clear space under an image?


Hey @all I have an image on the left side and a text on the right side of a container. My goal is to have the image stay on the left without anything appearing under it. This could be done with bootstrap obviously but with pure CSS, is a margin underneath the img a proper way to keep the text on the right side? The problem is that the margin has to be adjusted to the length of the paragraph. What would be a better way to do this?

HTML

  <div class="container test">
        <img src="https://images.pexels.com/photos/34950/pexels- 
             photo.jpg?cs=srgb&dl=abandoned-forest-hd-wallpaper-34950.jpg&fm=jpg"
             alt="">
        <h3>hola</h3>
        <p>I am a long paragraph, a very long one Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
            nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam.</p>
    </div>

CSS

.test {
      width: 300px;

      img {
        width: 100px;
        height: 100px;
        float: left;
        margin-bottom: 10rem;
      }
    }

Here is what it looks like: Screenshot with margin


Solution

  • Wrap the text content in it's own div and float that.

    .test {
      width: 300px;
    }
    
    img {
      max-width: 100px;
      float: left;
    }
    
    .wrap {
      float: left;
      width: 200px;
    }
    <div class="container test">
      <img src="http://www.fillmurray.com/460/300" alt="">
      <div class="wrap">
        <h3>hola</h3>
        <p>I am a long paragraph, a very long one Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam.</p>
      </div>
    </div>