Different image margins when floated left or right

49 Views Asked by At

How to set "smart" margins of image depending on its alignment? My website has pages in Rich Text Format, powered by django-ckeditor. When the user inserts an image (or a figure element with an image), he can align it right or left.

<figure class="image" style="float:right">
    <img height="180" width="280" src="/media/about/team/images.jpeg">
    <figcaption>Hello world!</figcaption>
</figure>

I want the image to be nicely aligned to the outer side of the text block. This means, the outer margin and padding should be 0, and the inner margin should be, say 1em.

Is it possible to do this with CSS styles? I think I met it on one website, but can't remember where.

The logic should be following: if the element already has style "float: left", the left margin is 1em, right margin 0, and vice versa.

1

There are 1 best solutions below

3
Alohci On BEST ANSWER

If you know that the float:left or float:right is in the HTML markup then you can use that as your selector for further styling. So:

figure {
  margin: 0;
}
[style*='float:left'] {
  margin-right: 1em;
}
[style*='float:right'] {
  margin-left: 1em;
}
hr { 
  clear:both;
}
section {
  text-align: justify; /* to show clearly where the margins are */
}
<section>
<figure class="image" style="float:left">
    <img height="180" width="280" src="/media/about/team/images.jpeg">
    <figcaption>Hello world!</figcaption>
</figure>
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. 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.
</section>
<hr>
<section>
<figure class="image" style="float:right">
    <img height="180" width="280" src="/media/about/team/images.jpeg">
    <figcaption>Hello world!</figcaption>
</figure>
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. 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.
</section>