search

Home  >  Q&A  >  body text

Using attribute selectors to select elements in CSS

<p>In CSS, is it possible to select elements via the HTML5 data attribute (e.g., <code>data-role</code>)? </p>
P粉143640496P粉143640496503 days ago541

reply all(2)I'll reply

  • P粉148434742

    P粉1484347422023-08-22 10:02:48

    It is also possible to select attributes regardless of their content in modern browsers.

    Use the following code:

    [data-my-attribute] {
       /* 样式 */
    }
    
    [anything] {
       /* 样式 */
    }
    

    For example: http://codepen.io/jasonm23/pen/fADnu

    Applicable to most browsers.

    Note that this can also be used within a JQuery selector, or using document.querySelector.

    reply
    0
  • P粉543344381

    P粉5433443812023-08-22 00:12:05

    If you mean using the attribute selector , of course you can:

    [data-role="page"] {
        /* 样式 */
    }
    

    There are a variety of attribute selectors that can be used in different scenarios, and these are detailed in the documentation I provide. Please note that although custom data attributes are a "new HTML5 feature",

    • Browsers generally have no problem supporting non-standard attributes, so you should be able to filter using attribute selectors; and

    • You don't have to worry about CSS validation either, since CSS doesn't care about non-namespace attribute names as long as it doesn't break selector syntax.

    reply
    0
  • Cancelreply