1

I would like to set the background image of a div regarding its class. The web I am developing should show a set of game cards. Each card is contained in a div and have a class like this:

<div class="card value suit>
</div>

Being the suit and value for instance clubs and five respectively. So for instance, for a div container like this:

<div class="card seven clubs>
</div>

I wonder if there is a way via CSS to set its background-image to this attribute without writing this for each card:

.card.seven.clubs {
    background-image:  url("../../images/seven_clubs.png");
}
MABC
  • 576
  • 2
  • 11
  • 29
  • 1
    You should have a look at SCSS and it's variables. Also check out this question: https://stackoverflow.com/questions/39518374/scss-variable-class-name – jdickel May 16 '18 at 14:42
  • Regardless, **NO**. SCSS will still output the same CSS. SCSS just makes it easier to write. – Paulie_D May 16 '18 at 14:45
  • i would suggest you take a look at https://stackoverflow.com/questions/15734546/using-html-data-attribute-to-set-css-background-image-url , to use html attributes like `
    ` then in css `background: url("../../images/" attr(value) "_" attr(suit) ".png");` but i think you would be better off setting the backgrounds in the inline css `
    `
    – Taki May 16 '18 at 15:16
  • background: url("../../images/" attr(value) "_" attr(suit) ".png"); this indeed does not work doesnt it? – MABC May 17 '18 at 13:48

1 Answers1

0

you can't really have dinamy classes with css only, you need some form or precompiler such as SASS to to convert from thing like

for every number do {
  generate number properties
}
for every suite do {
  generate suite css properties
}

to actual css code in the form of

.suite1{
  property: value;
}
.suite2{
  property:value
}
.number1{
  property:value
}

or you can use Javascript and dynamically set styles on it

var cards = document.getElementsByClassName('card');
for (var i = 0; i++; i < cards.length){
  var thisElementClasses = cards[i].classList;
  let imageUrl = '../../images/'+thisElementClasses[0]+'_'+'thisElementClasses[1]'+'.png';
  card[i].style.backgroundImage = imageUrl;
}
liviu blidar
  • 351
  • 4
  • 16