Home > other >  How to change an element's font-family without affecting it's ::before or ::after?
How to change an element's font-family without affecting it's ::before or ::after?

Time:04-02

A lot of sites use the ::before selector on an element to load icons via a client-downloaded font file, e.g.

div {
    font: 14px/1 FontAwesome;
}

div::before {
    content: "\f1c8";
}

Unfortunately the following rule also applies to the element's ::before pseudo-element, which breaks the icon display:

div {
    font-family: sans-serif !important;
}

It's not possible to :not(::before) (source), so how would you go about targeting an element, but not it's ::before?

This worked decently, but it misses the text (if any) inside the element:

div:not([class*="fa-"]) {
    font-family: sans-serif !important;
}

It may not even be possible. No JavaScript, please.

CodePudding user response:

It's not possible without then again overwriting the before and after again

div {
  font-family: sans-serif;
}

div::before,
div::after {
  font-family: serif;
}

Or you could just use the icon in another element entirely.

<span ></span>
<span>Text here</span>

And a s a sidenote :) Please use textelements for text, not divs (and span is also not a text element, it simply is an inline element without any semantic information)

CodePudding user response:

With @Termani's help above, this is how I solved the problem of injecting my preferred font into websites while doing minimal damage to most site's icons loaded via webfont files:

::before {
    font-family: FontAwesome, "Font Awesome", "Font Awesome 5 Pro",
    "Font Awesome 5 Free", "Material Icons", "Material-Design-Iconic-Font",
    "CBSi Fantasy icomoon", CBSi_Fantasy_icomoon, icon-moon, icons !important;
}

There are undoubtedly other font-family names that developers use, so the list will grow as I stumble upon them.

I'll update this answer if I find a better solution.

  • Related