Search code examples
htmlcssposition

Fix image to right of centered text without moving the text


From this JSFiddle you can see that if you press the 'toggle circle' button the circle which is inline with the text hides and shows. The text beside it moves as well because the div surrounding it centers the text using text-align: center;

function hide() {
  $('img').toggle();
}
div {
  text-align: center;
  background-color: grey;
  padding: 20px;
}
p {
  display: inline;
  color: white;
  vertical-align: top;
}
img {
  display: inline;
  width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button onclick="hide();">Toggle Circle</button>

<div>
  <p>Lorem Ipsum</p>
  <img src="https://upload.wikimedia.org/wikipedia/commons/1/13/Disc_Plain_red.svg">
</div>

I would like it so that the text is centered as if the circle is not there and then when the button is clicked the circle appears alongside it. Put simply I would like the centering of the text to not be affected by the circle even though it will still appear next to it.

How would I do this? Thanks.


Solution

  • If you can edit the markup, move <img> into <p>, then set it as img {position:absolute;} to take it out of the normal content flow. And use top, right values along with transform to put the image into correct place.

    Updated - https://jsfiddle.net/uuvLogcr/5/

    function hide() {
      $('img').toggle();
    }
    div {
      text-align: center;
      background-color: grey;
      padding: 20px;
    }
    p {
      display: inline;
      color: white;
      position: relative;
    }
    img {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translate(100%, -50%);
      width: 50px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <button onclick="hide();">Toggle Circle</button>
    
    <div>
      <p>
        Lorem Ipsum
        <img src="https://upload.wikimedia.org/wikipedia/commons/1/13/Disc_Plain_red.svg">
      </p>
    </div>