user42668
user42668

Reputation: 85

How to put an image after some text using CSS?

I wish to put an image after a few items in a Wordpress site. I don't want to place an image after all similar items, only specific ones.

Thankfully each specific item generates it's own css class.

I thought using :after would be the answer but i'm failing somewhere.

<div id="menu_4212" class="menu_content_classic">
<h5 class="menu_post">
    <span class="menu_title">Onion Soup</span>
    <span class="menu_dots"></span><span class="menu_price">€4.50</span>
</h5>

I want to place the image after "Onion Soup"

So I tried this approach to target specifically #menu_4212:

#menu_4212.menu_post.menu_title::after {
  content: url('..images/gluten_free.png')
}

I think i may have got the div hierarchy wrong, any ideas would be great.

Upvotes: 3

Views: 13198

Answers (3)

Vitalii Chmovzh
Vitalii Chmovzh

Reputation: 2943

If you want to do this, you can give your :after pseudo-element some display property and also specify it's dimensions. Then put image on the background. It will give you some flexibility for styling the image.

Something like this (style to your own needs):

#menu_4212 .menu_post .menu_title::after {
   content: '';
   display: block;
   width: 30px;
   height: 30px;
   background: url('..images/gluten_free.png') no-repeat center center;
   background-size: cover;
}

Upvotes: 0

Stickers
Stickers

Reputation: 78686

Technically you cannot insert an image tag in between the two <span> tags via CSS, let's say:

.menu_title::after {
  content: "NEW";
}

That will insert it to <span class="menu_title">Onion SoupNEW</span>

It will be the same if you're trying to insert an image:

.menu_title::after {
  content: url('..images/gluten_free.png');
}

The problem is your selectors #menu_4212.menu_post.menu_title::after, it targets everything is on the same element, e.g. <span id="menu_4212" class="menu_post menu_title">

With your markup you should do this, mind the gap.

#menu_4212. menu_post. menu_title::after {
  content: url('..images/gluten_free.png')
}

And be aware, with this method, you won't be able to control the size of the image via CSS. You can however use background images.

#menu_4212. menu_post. menu_title::after {
  content: "";
  display: inline-block;
  vertical-align: middle;
  width: 20px;
  height: 20px;
  background: url('..images/gluten_free.png') 0 0 no-repeat;
  background-size: contain;
}

In addition, you can also insert the image via .menu_post::after {...}, then use flexbox order property to reorder them, make the image to show in the middle of the spans visually.

Upvotes: 8

Chris J. Z&#228;hller
Chris J. Z&#228;hller

Reputation: 133

Try:

#menu_4212 .menu_post .menu_title::after {
  content: url('..images/gluten_free.png')
}

Your current code assumes the ID & 2 classes are all on the same element. You want to use the "descendant" syntax instead.

Upvotes: 1

Related Questions