如何使用DATA ATTRIBUTE将背景图像添加到带有HTML和CSS的锚标记中

如何使用DATA ATTRIBUTE将背景图像添加到带有HTML和CSS的锚标记中

问题描述:

I am trying to add a background image to an Anchor tag when value is "ENGLISH" and "FRENCH"

I was able to make it work when the echoed php value was a digit using DATA-ID this way

HTML AND PHP:

<li><a href="#" class="pjMbSelectorLocale" data-id="<?php echo 
$locale['id'];?>"><?php echo pjSanitize::html($locale['title']); ?></a></li>

CSS:

li a[data-id="1"]{
background- 
image:url("img/flags/united- 
kingdom.svg");
background-position: center;background-repeat: no-repeat;display: inline- 
block;
}

li a[data-id="2"]{
background-image:url("img/flags/france.svg");
background-position: center;background-repeat: no-repeat;display: inline- 
block;
}

now I am trying to do the same when the echoed value is not an ID (1 or 2) but a text ("English" and "French") with this statement:

<button>
  <a href="#" data-value="<?php echo $selected_lang;?>"></a>
</button>

And I can't seem to figure out how to manipulate it in css

Update: there seems to be a problem with the php, whenever I add the anchor tag, the echoed text disappears: initial php was:

<button>
<?php echo $selected_lang;?>
</button>

using dev tools, I can see the value being passed into the data-value and the css going with either options. but the browser doesn't not render the text nor the image


Solved

Solution:

the image was being hidden by a background-image:none default property and also I had to apply a height and width.

a[data-value="English"]{
background- 
image:url("img/flags/united- 
kingdom.svg");
background-position: center;background-repeat: no-repeat;display:inline- 
block;width: 20px;height: 20px;
}

Did you try:

li a[data-value='ENGLISH']{
    ...
}
li a[data-value='FRENCH']{
    ...
}