Search code examples
htmlcssvertical-alignment

How to position an element such that it neatly rests under a wrapped line


Using CSS, I want to be able to make the buttons move up if there is empty space (due to text wrapping).

The picture below illustrates the problem. I want the top button to be displayed a few pixels higher, as there is no text directly above it.

Instead, it is aligned with the bottom of text-which-is-only-present-on-the-right.

Is there a way of achieving this with CSS (I can change the HTML)?

Bad button alignment

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<div class="right">
  <button class="button-primary">Do this...</button>
</div>
<p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<div class="right">
  <button class="button-primary">Do that...</button>
</div>

CSS:

div.right {
  text-align: right;
}

Solution

  • div {
      display:inline-block;
      width:100%;
      border: 1px solid #000;  
    }
    
    p {
      display:inline;
    }
    
    .button-primary {   
      float:right;
    }
    <div>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
      <button class="button-primary">Do this...</button>
    </div>
    <div>
      <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
      <button class="button-primary">Do that...</button>
    </div>