Add image left and right to link with CSS class

2932 views css
5

i need to add an small image to the left and right from a hyperlink. This will be reused several times with different images, so I need to do it in CSS with classes. I succeeded already to either the left http://jsfiddle.net/XAh2d/9257/

.fuss {background: transparent url(https://elternwerkstatt.domaincontrol.at/wp-content/uploads/2018/09/fusspaar-rot_18px.png) center left no-repeat; padding-left: 20px;}     

or to the right http://jsfiddle.net/k59zhwg3/1/

.fuss {background: transparent url(https://elternwerkstatt.domaincontrol.at/wp-content/uploads/2018/09/fusspaar-rot_18px.png) center right no-repeat; padding-right: 20px;}

but as soon i try to use two classes for left AND right, it didnt work, only one image shows up: http://jsfiddle.net/7jcqxa3v/10/

.fuss-rechts {background: transparent url(https://elternwerkstatt.domaincontrol.at/wp-content/uploads/2018/09/fusspaar-rot_18px.png) right no-repeat; padding-right: 20px;}
.fuss-links {background: transparent url(https://elternwerkstatt.domaincontrol.at/wp-content/uploads/2018/09/fusspaar-rot_18px.png) left no-repeat; padding-left: 20px;}

 in HTML: <a class="fuss-links fuss-rechts" target="_blank" href="https://elternwerkstatt.domaincontrol.at">hier mein link</a>

Any help appreciated! Thank you

answered question

2 Answers

10

Yes, this is expected behavior. The CSS class fuss-links is overwriting the background rule set by fuss-rechts since it comes 2nd in the stylesheet, since CSS rulesets prioritize rules that come last (hence the C for cascading in CSS).

To my knowledge, you cannot achieve the desired effect using just the CSS background rule, since it does not allow you to repeat elements only on the edges, you can either never repeat or repeat across the entire width (source: https://css-tricks.com/almanac/properties/b/background-repeat/).

My suggestion would be to move the images to <img> tags inside the <a> tag and to use position: absolute; to achieve the effect you want. You can see any example here:

https://jsfiddle.net/7jcqxa3v/22/

posted this
2

Your css class should be this:

    .fuss {
       background: transparent;
       background-image: url(https://elternwerkstatt.domaincontrol.at/wp-content/uploads/2018/09/fusspaar-rot_18px.png), url(https://elternwerkstatt.domaincontrol.at/wp-content/uploads/2018/09/fusspaar-rot_18px.png);
       background-position:left,right;
       background-repeat: no-repeat, no-repeat;
       padding-left:20px;
       padding-right:20px;
     }

posted this

Have an answer?

JD

Please login first before posting an answer.