Multiple class attributes in HTML

后端 未结 2 1533
予麋鹿
予麋鹿 2020-12-17 09:29

What happens when an element has multiple class attributes?

I\'

2条回答
  •  执念已碎
    2020-12-17 10:15

    What happens when an element has multiple class attributes?

    When an attribute is declared multiple times for a single element (which is invalid HTML, by the way), behavior-wise the first value will override all subsequent values for the same attribute. So in this case, your element will only have the classes one two three.

    This behavior is explained in the HTML5 spec, 8.2.4.35 Attribute name state, "... if there is already an attribute on the [element] with the exact same name, then this is a parse error and the new attribute must be removed..."

    If you know the correct way of adding a class to this snippet (WordPress plugin), then that would also be appreciated!

    Typically, if you need to add custom classes dynamically to your WordPress posts, you hook onto the post_class filter and manipulate the $classes array as necessary. Here's what it roughly looks like in my themes:

    function nv_post_class( $classes ) {
        // Most recent post on the front page
        global $count;
        if ( is_home() && 1 == $count )
            $classes[] = 'latest-post';
    
        return $classes;
    }
    
    add_filter( 'post_class', 'nv_post_class' );
    

    If you only need to add one or more static classes, pass them as a space-delimited string directly to post_class():

    >

    More on this in the WordPress Codex.

提交回复
热议问题