How to Use a Tag or Element Selector in CSS3

Tag (or element) selectors are character sequences in CSS3 that you use to choose tags such as <h1> and <p>. In fact, you can select any HTML tag this way. A tag selector always relies on the tag name, such as p or h1. However, there are some interesting tag selector combinations you should know about.

The following list tells you about tag selectors that you can use in addition to the simple tag selector.

  • Tag,Tag: Separating two tags with a comma means selecting both tags, regardless of where they appear in the document. For example, using p,div would select all <p> and <div> tags within the document.

  • Tag>Tag: Separating two tags with a greater-than sign (>) tells the browser to select a tag that has another tag as a parent. For example, if you have <div><p /></div> and use div>p, the browser will select the <p> tag.

  • Tag Tag: Separating two tags by a space tells the browser to select a tag that appears within another tag. This selector differs from using a greater than sign in that the first tag need not directly appear immediately before the second tag.

    For example, if you have <div><span><p /></span></div> and use div>p, the browser won’t select anything. However, if you use div p instead, the browser will select the <p> tag.

  • Tag+Tag: Separating two tags with a plus sign (+) tells the browser to select a tag that appears immediately after another tag. For example, if you have <div /><p /> and use div+p, the browser will select the <p> tag. Notice that the <p> tag doesn’t appear within the <div> tag, it appears after the <div> tag.

  • Tag~Tag: Separating two tags with a tilde (~) tells the browser to select every tag that appears after another tag. For example, if you have <div /><p /><p /> and use div~p, the browser will select both <p> tags. This differs from div+p, which tells the browser to select only the first <p> tag that follows the <div> tag.

  • :root: Selects the root element of the document. The root element depends on the document type. This selector is normally used with XML documents, but you could potentially use it with any document type.

blog comments powered by Disqus
Advertisement

Inside Dummies.com