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");
}
4
  • 1
    You should have a look at SCSS and it's variables. Also check out this question: stackoverflow.com/questions/39518374/scss-variable-class-name Commented May 16, 2018 at 14:42
  • Regardless, NO. SCSS will still output the same CSS. SCSS just makes it easier to write. Commented May 16, 2018 at 14:45
  • i would suggest you take a look at stackoverflow.com/questions/15734546/… , to use html attributes like <div class="card" value="07" suit="clubs"> 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 <div class="card" style="background..."> Commented May 16, 2018 at 15:16
  • background: url("../../images/" attr(value) "_" attr(suit) ".png"); this indeed does not work doesnt it? Commented May 17, 2018 at 13:48

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.