HTML/CSS How to apply CSS to “a” with custom data

2019-05-28 21:53发布

问题:

I already know how to apply CSS to custom data attributes but in my case it just doesn't seem to work. I don't want to select by class but by data-store attribute.

HTML

<a data-store="{&quot;dialogURI&quot;:&quot;\/messages\/compose\/dialog\/&quot;}" href="#"></a>

CSS

[data-store=" {&quot;dialogURI&quot;:&quot;\/messages\/compose\/dialog\/&quot;}"]{
position:fixed!important;
bottom:0px!important;
}

But it doesn't seem to work. Any help would be greatly appreciated.

回答1:

The &quot;s you see in the HTML attribute are character references for double quotes. They are represented in a CSS attribute selector as literal double quotes, not the HTML entities, since HTML entities pertain to HTML only. Since the value contains double quotes, use single quotes to delimit the value in your attribute selector so you don't have to escape the double quotes in the value.

The backslashes in the attribute value need to be escaped, so \ becomes \\.

There is also a wayward leading space in your attribute selector that should be removed.

Hence:

[data-store='{"dialogURI":"\\/messages\\/compose\\/dialog\\/"}'] {
position:fixed!important;
bottom:0px!important;
}

As mentioned by others, if the element has a class and you can identify that element using that class and some context, it's a better idea to do that. However, the element in question may not always appear in the same context or may not be the only one with the class, and you don't always have control over the markup — so there is nothing wrong with using an attribute selector if you don't have any other options.



回答2:

Why not just use the class? Selecting by data attribute is a very bad idea, especially in that form.

.hello {
    position: fixed !important;
    bottom: 0px !important;
}

Btw, you should try to avoid !important...

Also look at

~= 

in your css. It allows spaces in the rel attribute.