简体   繁体   中英

CSS nth-child() working strange?

There is a HTML structure with two fieldset , like in the jsfiddle example below. The following CSS lines

#aboutus > fieldset:nth-child(2) li {
    text-align: left;
}

can affect to the second fieldset 's elements in jsfiddle, but on the page should add this for the resullt:

#aboutus > fieldset:nth-child(4) li {
    text-align: left;
}

there are no 4th fieldset, but only in this case apply the text-align: left; to the object ( li ).

http://jsfiddle.net/EQPTS/

You want to use nth-of-type not nth-child , the former considers the element type, the latter its position and eligibility.

Demo Fiddle

nth-of-type

The :nth-of-type CSS pseudo-class matches an element that has an+b-1 siblings with the same element name before it in the document tree, for a given positive or zero value for n, and has a parent element. See :nth-child for a more thorough description of the syntax of its argument. This is a more flexible and useful pseudo selector if you want to ensure you're selecting the same type of tag no matter where it is inside the parent element, or what other different tags appear before it.

nth-child

The :nth-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings before it in the document tree, for a given positive or zero value for n, and has a parent element.

This can more clearly be described this way: the matching element is the bth child of an element after all its children have been split into groups of a elements each.

The nth-child selector, selects nth element, with the same type of the selector. 2nd child is the first fieldset. You need to use nth-of-type and not nth-child .

#aboutus li {
    text-align: right;
}
#aboutus > fieldset:nth-of-type(2) li {
    text-align: left;
}

This works for you.

Fiddle: http://jsfiddle.net/praveenscience/EQPTS/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM