csscss-paged-media

CSS floats: how to keep the float near the text it belongs to?


I've got a procedure that consists of steps. Some steps are accompanied by an image.

    <p class="imagefloatright"><img src="step 1.png"/></p>
    <ol>
        <li>
          <p>Step 1</p>
          <p class="imagefloatright"><img src="step 2.png"/></p>
        </li>
        <li>
          <p>Step 2</p>
          <p>Step 3</p>
        </li>
    </ol>

and my CSS:

p.imagefloatright img {
    float: right;
    clear: both;
}

This is the default output. Images don't stay with the steps they belong to, the text for step 2 is put alongside image 1:

enter image description here

I want the image that belongs to step 2 to be vertically aligned with step 2:

enter image description here

In the past, I've achieved my desired result in XSL-FO by inserting a full-width block with height =0 before each floated image.

Can I achieve my desired layout using CSS commands? Or do I need to insert a block in the HTML before I apply the CSS to the HTML?


Solution

  • To clear the float which contains the dynamic content ie. image can have dynamic height, you'll need to clear the parent element itself.

    .imagefloatright {
      clear: both;
    }
    .imagefloatright img {
      float: right;
    }
    

    It means that you need to use clear on the element which contains the floating elements.


    For brevity, I would rename it like:

    .clearfix {
      clear: both;
    }
    .float-right {
      float: right;
    }
    

    HTML

    <p class="clearfix"><img class="float-right" src="step 1.png"/></p>
    <ol>
        <li>
          <p>Step 1</p>
          <p class="clearfix"><img class="float-right" src="step 2.png"/></p>
        </li>
        <li>
          <p>Step 2</p>
          <p>Step 3</p>
        </li>
    </ol>
    

    Here's a demo.