Css style by data attribute

How to select elements by data attribute using CSS?

CSS (Cascading Style Sheets) is an essential tool for web developers to enhance the visual looks of the web pages. With CSS, we can customize the layout, color scheme, and typography of the website. CSS provides multiple ways to target and style specific HTML elements based on their attributes. One of the most useful and powerful methods to select elements is by using data attributes.

What are data attributes?

Data attributes are HTML attributes that provide additional information about an element, that information is not visible to the user but can be accessed by scripts or CSS. These attributes begin with the word «data-» followed by a descriptive name. Data attributes can be used to store information that is not visible to the user but can be accessed by scripts or CSS.

For example, suppose we have a list of products, and we want to apply different styles to products with different ratings. We can use a data attribute to store the rating value and target it with CSS.

Читайте также:  Javascript http запрос post

How to use data attributes in HTML?

To use data attributes in HTML, we need to add the «data-» prefix to the attribute name. Here is an example −

In the above example, we have added a data-rating attribute to each list item that stores the rating value of each product. This data can be accessed and manipulated using CSS.

How to select elements by data attribute using CSS?

To select elements by data attribute using CSS, we use the attribute selector. The attribute selector allows us to target elements based on their attribute value.

Syntax

In the above syntax, «attribute» refers to the data attribute that we want to target, and «value» refers to the value of the data attribute. For example, If we want to apply a different background color to products with a rating of 6. For doing this we will use the following CSS code −

In the above code, we are using the attribute selector to target list items with a data-rating attribute value of 6 and applying a red background color to them.

Example 1

Here is an example to select elements by data attribute using CSS.

Example 2

Here is another example to select elements by data attribute using CSS. In this example, we are using the data-my-data attribute to store information about tabs. The first CSS rule selects all elements that have a data-my-data attribute and applies some basic styling to them. The second rule selects only elements with a data-my-data attribute and applies a hover style to them. The third rule selects only elements with a data-my-data attribute and applies the CSS style.

    body < text-align:center;>[data-my-data] < border: 1px solid black; padding: 10px; cursor: pointer; >[data-my-data]:hover < background-color: red; color: white; >[data-my-data="d-tab"] 

Hover over the below DIVs to see the changes

First Tab Data
Second Tab Data
Third Tab Data

Conclusion

By storing additional data in HTML and targeting it with CSS, we can create interactive and dynamic web pages that are tailored to the specific needs. Using data attributes in HTML and selecting elements by data attribute using CSS can be a powerful way to customize the appearance of the web pages.

Источник

Using data attributes

HTML is designed with extensibility in mind for data that should be associated with a particular element but need not have any defined meaning. data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.

HTML syntax

The syntax is simple. Any attribute on any element whose attribute name starts with data- is a data attribute. Say you have an article and you want to store some extra information that doesn’t have any visual representation. Just use data attributes for that:

article id="electric-cars" data-columns="3" data-index-number="12314" data-parent="cars">article> 

JavaScript access

Reading the values of these attributes out in JavaScript is also very simple. You could use getAttribute() with their full HTML name to read them, but the standard defines a simpler way: a DOMStringMap you can read out via a dataset property.

To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase).

const article = document.querySelector("#electric-cars"); // The following would also work: // const article = document.getElementById("electric-cars") article.dataset.columns; // "3" article.dataset.indexNumber; // "12314" article.dataset.parent; // "cars" 

Each property is a string and can be read and written. In the above case setting article.dataset.columns = 5 would change that attribute to «5» .

CSS access

Note that, as data attributes are plain HTML attributes, you can even access them from CSS. For example to show the parent data on the article you can use generated content in CSS with the attr() function:

article::before  content: attr(data-parent); > 

You can also use the attribute selectors in CSS to change styles according to the data:

article[data-columns="3"]  width: 400px; > article[data-columns="4"]  width: 600px; > 

You can see all this working together in this JSBin example.

Data attributes can also be stored to contain information that is constantly changing, like scores in a game. Using the CSS selectors and JavaScript access here this allows you to build some nifty effects without having to write your own display routines. See this screencast for an example using generated content and CSS transitions (JSBin example).

Data values are strings. Number values must be quoted in the selector for the styling to take effect.

Issues

Do not store content that should be visible and accessible in data attributes, because assistive technology may not access them. In addition, search crawlers may not index data attributes’ values.

See also

  • This article is adapted from Using data attributes in JavaScript and CSS on hacks.mozilla.org.
  • Custom attributes are also supported in SVG 2; see SVGElement.dataset and data-* for more information.
  • How to use HTML data attributes (Sitepoint)

Found a content problem with this page?

This page was last modified on Jun 30, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Attribute selectors

The CSS attribute selector matches elements based on the element having a given attribute explicitly set, with options for defining an attribute value or substring value match.

The case sensitivity of attribute names and values depends on the document language. In HTML, attribute names are case insensitive, as are spec-defined enumerated values. The case-insensitive HTML attribute values are listed in the HTML spec. For these attributes, the attribute value in the selector is case-insensitive, regardless of whether the value is invalid or the attribute for the element on which it is set is invalid.

If the attribute value is case sensitive, like class , id , and data-* attributes, the attribute selector value match is case-sensitive. Attributes defined outside of the HTML specification, like role and aria-* attributes, are also case-sensitive. Normally case-sensitive attribute selectors can be made case-insensitive with the inclusion of the case-insensitive modifier ( i ).

Syntax

Represents elements with an attribute name of attr.

Represents elements with an attribute name of attr whose value is exactly value.

Represents elements with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value.

Represents elements with an attribute name of attr whose value can be exactly value or can begin with value immediately followed by a hyphen, — (U+002D). It is often used for language subcode matches.

Represents elements with an attribute name of attr whose value is prefixed (preceded) by value.

Represents elements with an attribute name of attr whose value is suffixed (followed) by value.

Represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string.

Adding an i (or I ) before the closing bracket causes the value to be compared case-insensitively (for characters within the ASCII range).

[attr operator value s] Experimental

Adding an s (or S ) before the closing bracket causes the value to be compared case-sensitively (for characters within the ASCII range).

Examples

CSS

a  color: blue; > /* Internal links, beginning with "#" */ a[href^="#"]  background-color: gold; > /* Links with "example" anywhere in the URL */ a[href*="example"]  background-color: silver; > /* Links with "insensitive" anywhere in the URL, regardless of capitalization */ a[href*="insensitive" i]  color: cyan; > /* Links with "cAsE" anywhere in the URL, with matching capitalization */ a[href*="cAsE" s]  color: pink; > /* Links that end in ".org" */ a[href$=".org"]  color: red; > /* Links that start with "https://" and end in ".org" */ a[href^="https://"][href$=".org"]  color: green; > 

HTML

ul> li>a href="#internal">Internal linka>li> li>a href="http://example.com">Example linka>li> li>a href="#InSensitive">Insensitive internal linka>li> li>a href="http://example.org">Example org linka>li> li>a href="https://example.org">Example https org linka>li> ul> 

Result

Languages

CSS

/* All divs with a `lang` attribute are bold. */ div[lang]  font-weight: bold; > /* All divs without a `lang` attribute are italicized. */ div:not([lang])  font-style: italic; > /* All divs in US English are blue. */ div[lang~="en-us"]  color: blue; > /* All divs in Portuguese are green. */ div[lang="pt"]  color: green; > /* All divs in Chinese are red, whether simplified (zh-Hans-CN) or traditional (zh-Hant-TW). */ div[lang|="zh"]  color: red; > /* All divs with a Traditional Chinese `data-lang` are purple. */ /* Note: You could also use hyphenated attributes without double quotes */ div[data-lang="zh-Hant-TW"]  color: purple; > 

HTML

div lang="en-us en-gb en-au en-nz">Hello World!div> div lang="pt">Olá Mundo!div> div lang="zh-Hans-CN">世界您好!div> div lang="zh-Hant-TW">世界您好!div> div data-lang="zh-Hant-TW">世界您好!div> 

Result

HTML ordered lists

The HTML specification requires the type attribute to be matched case-insensitively because it is primarily used in the element. Note that if a modifier is not supported by the user agent, then the selector will not match.

CSS

/* Case-sensitivity depends on document language */ ol[type="a"]  list-style-type: lower-alpha; background: red; > ol[type="b" s]  list-style-type: lower-alpha; background: lime; > ol[type="B" s]  list-style-type: upper-alpha; background: grey; > ol[type="c" i]  list-style-type: upper-alpha; background: green; > 

HTML

ol type="A"> li> Red background for case-insensitive matching (default for the type selector) li> ol> ol type="b"> li>Lime background if `s` modifier is supported (case-sensitive match)li> ol> ol type="B"> li>Grey background if `s` modifier is supported (case-sensitive match)li> ol> ol type="C"> li> Green background if `i` modifier is supported (case-insensitive match) li> ol> 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • attr()
  • Selecting a single element: Document.querySelector() , DocumentFragment.querySelector() , or Element.querySelector()
  • Selecting all matching elements: Document.querySelectorAll() , DocumentFragment.querySelectorAll() , or Element.querySelectorAll()
  • Case-insensitive attribute selector values on WHATWG

Found a content problem with this page?

This page was last modified on Jun 29, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Оцените статью