Home > Net >  Reduce css code when only changing image location
Reduce css code when only changing image location

Time:01-04

We have a growing css file with what seems like a lot of unnecessary duplication and I would like to know if there is some way to reduce this

.upsidedownsmile::before {
    mask: url(/public/img/svg/emoji-smile-upside-down.svg) no-repeat 50% 50%;
    -webkit-mask: url(/public/img/svg/emoji-smile-upside-down.svg) no-repeat 50% 50%;
}

.people::before {
    mask: url(/public/img/svg/people.svg) no-repeat 50% 50%;
    -webkit-mask: url(/public/img/svg/people.svg) no-repeat 50% 50%;
}

Essentiall whats happening is we are just mapping some classes to some SVGs so that we can use them as icons through the website by calling

<i ></i>

This all works well

The issue I think is that we could heavily reduce the amount of code.

The problem is I do not know of any way to reduce

Every class looks exactly the same and spans 100's of lines for seemingly no reason the only different between classes is the image location

I have tried to google some things like using css variables, inheritance.

Not very fruitful results I think the problem is I am not quite sure the terminology of what it is im looking for

CodePudding user response:

Less symbols:

:root {
    --a: url(/public/img/svg/emoji-smile-upside-down.svg) no-repeat 50% 50%;
    --b: url(/public/img/svg/people.svg) no-repeat 50% 50%;
}
.upsidedownsmile::before {
    mask: var(--a);
    -webkit-mask: var(--a);
}
.people::before {
    mask: var(--b);
    -webkit-mask: var(--b);
}

Does it work?

CodePudding user response:

Using a few lines of JavaScript would make this job easy.

Set the element's classes exactly as their path. Then loop through them and set their mask path using className

const icons = document.querySelectorAll('p');

icons.forEach(icon=>{
    icon.style.mask = `url(/public/img/svg/${icon.className}) no-repeat 50% 50%;`
})
<i ></i>
<i ></i>

  •  Tags:  
  • css
  • Related