I know I can solve the problem below using <img />
and PHP
(or javascript
for that matter), but I'd like to solve it using just CSS
, if I can.
I have marked up a language menu, in which I would like a flag icon to appear beside each named language.
Ideally, I would like to not have to add a new line to the CSS, every time I add a new language.
But is there any way - using attr()
or CSS Custom Properties or some other method - that I can have the browser derive the correct background-image for each list item, using just (e.g.) class="fr"
and data-language="fr"
?
N.B. I am quite prepared for this to be beyond the current capabilities of CSS - but I am curious to find out if there is any inventive way of approaching this.
.language li {line-height: 40px;}
.language li::before {content:''; display:inline-block; position:relative; width:27px; height:27px; margin-right:9px; vertical-align:middle; background-color: rgb(191,191,191); border-radius:3px;}
.language li.de::before {background-image: url('/flags/de.png');}
.language li.en::before {background-image: url('/flags/en.png');}
.language li.es::before {background-image: url('/flags/es.png');}
.language li.fr::before {background-image: url('/flags/fr.png');}
<div class="language">
<h2>Select Language:</h2>
<ul>
<li class="en" data-language="en">English</li>
<li class="de" data-language="de">Deutsch</li>
<li class="es" data-language="es">Español</li>
<li class="fr" data-language="fr">Français</li>
</ul>
</div>
Additional Information:
My first approach was inadequate because it did not allow the flag icons to have rounded corners:
.language li {
background-position:0 center;
background-size: 27px 27px;
background-repeat: no-repeat;
padding-left:36px;
}
.language li.de {background-image: url('/flags/de.png');}
.language li.en {background-image: url('/flags/en.png');}
.language li.es {background-image: url('/flags/es.png');}
.language li.fr {background-image: url('/flags/fr.png');}
<div class="language">
<h2>Select Language:</h2>
<ul>
<li class="en" data-language="en">English</li>
<li class="de" data-language="de">Deutsch</li>
<li class="es" data-language="es">Español</li>
<li class="fr" data-language="fr">Français</li>
</ul>
</div>
But I am happy to skip the rounded corners if there is any potential here for achieving what I am aiming for.
Currently, it is not possible without Javascript or any other programming language. Hopefully in the future we will be able to by using the attr()
function, to get the attribute value from the element.
When using a pseudo-element
, it gets the attribute from the original element. So you can do background-image: attr('data-bg' 'url')
to get the data-bg
attribute and treat it as a URL.