Is it possible to use string macros in CSS?

There is a part of my site where I use the country flag as an icon for a list item.

For example, I have:

<ul>
  <li id="at">Austria</li>
  <li id="de">Germany</li>
</ul>

The accompanying CSS looks like this:

#at {
  list-style-image: url('at.png');
}
#de {
  list-style-image: url('de.png');
}

Can I replace this with a macro so that I don’t have to redefine CSS for each country? Something like a C-style macro would be awesome, but I'm not sure if CSS supports this.

t

#_country {
  list-style_image: url('_country.png');
}
+3
source share
6 answers

CSS alone does not do this, but you can always serve CSS from a PHP script or similar, doing server-side macro processing to create individual rules from a list of countries.

+7
source

CSS , . , ( ) , .

, CSS attr(), content, - :

.languages {
    background-image: attr(id) ".jpg";
}
+1

: .

: JavaScript , JavaScript, ...

PHP, Perl, Python ( *.css), -, , / 3 .

, ;) , , , .

+1

:

<!-- our lovely list-style-image function -->
<script>
  function set_list_country(list, country) {
    list.style.list-style-image = 'url("'+country+'.png")';
  }
</script>

<!-- country list -->
<ul>
  <li id="at">Austria</li>
  <li id="de">Germany</li>
</ul>

<!-- country list styling -->
<!-- note: this goes below your list, or else create onload function -->
<script>
  set_list_country(document.getElementById('at'), 'at');
  set_list_country(document.getElementById('de'), 'de');
</script>

.

0

, CSS, CSS - , CSS-.

javascript-, Andrejs, , CSS-, PHP.

0

CSS script . javascript .

, JS , .... , js - - "2.0"!

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Untitled Page</title>
  <script type="text/javascript">

     function initFlags() {

      var flagListItems = document.getElementsByTagName("li");

      for (var i = 0; i < flagListItems.length;  i++ )
      {
         var li = flagListItems[i];

        // use any prop you want to build the url - i used an expando one
        // just because i thought it made the code more readable.


        var f = li.getAttribute("flag");

        if (f == "" || f == null)  continue;

        li.style.listStyleImage = 'url(' + f + '.png)';

       }

    </script>
    </head>
    <body onload="initFlags()">
      <ul>
        <li id="at" flag="au">Austria</li>
        <li id="de" flag="de">Germany</li>
      </ul>
    </body>
</html>
0

Source: https://habr.com/ru/post/1708076/


All Articles