官术网_书友最值得收藏!

The power of CSS3 selectors

CSS selectors are very powerful and come in handy when formatting an HTML document. Using selectors is sometimes tricky, as selecting exactly what you want, and then ensuring that the style rules applied are affecting just the elements that you intended, is a tedious mission. But when done properly with the right selectors, the outcome is very rewarding. Mastering the use of selectors will result in a less complex CSS, minimizing the probability of having redundant styles and over-defining the HTML with classes and IDs, thus ensuring a better performance. The selector can simply be an HTML element, a class, an element ID, or it can even be the element's position in the DOM.

The following is a list of CSS selectors; we will start with the basics and get to the new selectors introduced in CSS3:

  • The asterisk (*) symbol: This is the catch-all selector, called the universal type selector, and is used to target every element in the document. It is often used with CSS Reset to reset all the default styles.
    * { margin: 0; }
  • The HTML element: It is called the type selector and is used to select all the elements in the document according to their type. For example, the following selector will target every <p> element in the DOM, change the color of the text to red, and underline it.
    p { color: red; text-decoration: underline; }
    Tip

    Using the <body> element as a selector will target the document's body, thereby selecting every element as if you are using the asterisk (*).

  • The ID selector: It is specified by the value in the id attribute of the element prefixed with the hash (#) symbol. The ID should be the element's name and, more importantly, it must be unique. The name should be a clear reference to the element. For instance, it would be quite clear to have an id value of mainMenu for a nav element. For example:
    <nav id="mainMenu"></nav>
    

    Moreover, being unique means that logically there should be no other element with an id value of mainMenu on the page. Since the id should always be unique, the selector will target only one element in the HTML document. For example, if you have a <div> element with an id value of logo as follows:

    <div id="logo"></div>

    Then the corresponding selector will be:

    #logo { float: left; width: 200px; } 
  • The class selector: It is specified by the name of a class prefixed with a period (.) and targets all the elements with the matching class name. The basic syntax for this selector is as follows:
    .highlighted { font-weight: bold; background-color:yellow; }

Any element with this class name will have bold text in a yellow background color. Classes should be applied when you want to style more than one element, specifically, a set of elements that have something in common. Bear in mind that contrary to the id property, the class name can never be used to uniquely identify an element. Moreover, the class property may have more than a single value; similarly, the same class may apply to more than one element. Although the use of class selectors may seem general, you can use it in a more specific manner by prefixing it with a type selector. For example, the following code snippet will target only the <div> elements that have the class highlighted:

div.highlighted { font-weight: bold; background-color: yellow; } 

Also, you can chain class selectors to target all the elements that have all of the specified classes.

Attribute selectors

The attribute selector is used to select elements based on their attributes. It checks whether an attribute is present; if yes, it checks the value of the attribute. The attribute should be enclosed within square braces. If the square braces contain only the name of the attribute, it will check if the attribute exists on the element. That's why it's also called the existence selector. In the following code snippet, the selector will target only the anchor elements having the title attribute:

a[title] { text-decoration: none; color: #000; }

The preceding syntax is helpful when checking for attributes that do not hold a value. If you remember, in the previous chapter we mentioned that some attributes do not need a value, such as the required attribute with the <input> elements, or the loop attribute with the audio and video elements. The following selector will look for all the audio elements that have the loop attribute and hide it:

audio[loop] { display: none; }

To target the element(s) that exactly matches the specified attribute value, we will use the equality attribute marked with an equal symbol (=) and the value wrapped within quotes. So, if we want to target all input elements that have the value email in their type attribute, the syntax will look like the following:

input[type="email"] { text-decoration: none; color: #000; }

Also, under the attribute selector category, we have the prefix or the "starts with" attribute selector, which is used to check if an attribute has a value that starts with some value. The following syntax will match all the images that have an id value starting with home. For example, if you want to target all the images in your home page, you can add home to the id, thus having homeLogo, homeBanner, and so on, and apply a margin of 10 px to it:

img[id^='home'] { margin:10px; }

Similarly, we have the suffix selector or the "ends with" attribute selector, which will select all the elements whose attribute ends with the value you specify. The suffix selector is marked with the dollar ($) symbol before the equal (=) sign, and the syntax will look as follows:

a[href$=".jpg"] { color: red; }

This will target all the anchor elements whose href attribute holds a value that ends with .jpg.

Another attribute selector is the substring selector, also known as the "contains" selector. As the name suggests, it matches the attribute value containing the value specified in the selector. It is marked with the asterisk (*) symbol before the equal (=) sign, and the syntax will look as follows:

ul[id*="Nav"] { float: left; list-style-type: none; }

The preceding syntax will match all the <ul> elements that have an ID containing the string Nav. For example, you have multiple <ul> elements used for navigational purposes and marked with IDs such as secondaryNav, sidebarNav, and so on.

Also, we have the hyphen selector, marked with |=, which is used to match all the attribute values that are exactly equal and is immediately followed by a hyphen. You might use this selector rarely but a typical use for it would be with values that include a hyphen, for example, the lang attribute. The following listing will target all the elements with a value that exactly matches "en", additionally followed by a hyphen, and will return en, en-us, en-uk, and so on:

ul[lang|="en"] { display: none; }

The last attribute selector would be the whitespace selector, which targets the specified attribute value that exactly matches in a space-delimited list of values. In the following code snippet, we have a <p> element with a custom data- attribute, containing three space-separated values, named new events local, and the selector will match this element since its data-post-type value matches exactly the value specified as events.

The following is the HTML code:

<p data-post-type="new events local"></p>

And the CSS code is as follows:

p[data-post-type~="events"] { float: left; color: red }
Note

Note that, with HTML5, any attribute starting with data- is valid, unlike its predecessor that considers only the recognized attributes as valid.

Combinator selectors

A CSS selector can contain multiple selectors, that is, a combination of simple selectors. A combinator selector contains more than one simple selector joined by a combinator. The combinator is a symbol that represents the relationship between the selectors. We already had three different combinators in CSS2, and CSS3 added one extra. Listed as follows are the four selectors, the combinators used, and what each selector matches:

The preceding selectors are described as follows:

  • The Descendant selector: It is marked by a space character as a combinator and it will select all elements that are descendants of a specified element. It is as if we are applying an additional filter on the first simple selector. The first selector represents the parent element, and the second is the child (descendant) element you are trying to match. For example, the following code snippet will match all the anchor elements that have the <li> element as their parent:

    The HTML code is as follows:

    <ul>
        <li><a href="#">Item 1</a></li>
        <li><a href="#">Item 2</a></li>
        <li><a href="#">Item 3</a></li>
    </ul>

    The CSS selector is as follows:

    li a { text-decoration: none; color: #000; } 
  • The Direct Descendant selector: It is marked by the greater-than (>) sign as a combinator and has the basic form E>F, which matches every F element that is a direct descendant (child) of the E element. In the following code snippet, only the <p> elements that are immediate children of the <div> element are going to be colored blue while the rest are not.

    The HTML code is as follows:

    <div>
        <p>some content inside a div</p>
    </div>
    <p> standalone content …</p>
    <div>
        <p> contentinside a div </p>
    </div>
    <header>
        <p> content inside a header </p>
    </header>

    The CSS code is as follows:

    div > p { color: Blue; } 
  • The Adjacent Sibling selector: It is marked by a plus (+) sign as a combinator, and matches all the sibling elements that are immediately following the parent element. So, there can be no elements in between the sibling elements. If it is a bit complex, the following example will explain it. The selector will apply red color only to one <p> element.

    The HTML code is as follows:

    <h1>Heading</h1>
    <p>This p element is a sibling and adjacent to the h1 
    </p>
    <p>This p element is a sibling but not adjacent to the h1
    </p>

    The CSS code is as follows:

    h1 + p { color: Red; } 
  • The General Sibling selector: It is marked by the tilde (~) sign as a combinator, and is a new addition in CSS3. It is used to select all the elements that are siblings of a given element. So, if we apply the selector to the HTML in the preceding example, both the <p> elements will match and will be colored red, as they are both siblings of h1.
    h1 ~ p { color: Red; } 

Pseudo-class selectors

A pseudo-class is similar to a class but, since it is in-built, you do not have to explicitly add it in the HTML code. Also, it differs in syntax; a class selector is preceded by a period (.), whereas a pseudo-class is preceded by a colon (:). In its basic form, a pseudo-class selector will take the following form:

selector:pseudo-class { property: value }

You can specify a pseudo-class without a selector, and it will invoke the default type selector. So, if we specify :hover alone, it will match all the elements and apply the style rule to anything in the document that can be hovered on. Else, you can be more detailed and apply the pseudo-class selector to a specific HTML element. For example, the following code snippet will apply a pink color on all the <p> elements when hovered over:

p:hover { color: pink; }

Pseudo-classes existed in CSS prior to CSS3 and you are most probably familiar with the famous :hover, :visited, and :active pseudo-classes that represent the different states of the anchor element. CSS3 introduced many more powerful pseudo-classes such as :required, :valid, :nth-child(n), :first-child, :last-child, :only-child, :first-of-type, :last-of-type, and several others.

Pseudo-element selectors

Pseudo-elements represent parts of elements, such as the first line of a paragraph, or the part that appears after an element. Similar to a pseudo-class that acts as a class, a pseudo-element behaves as an element but is in-built and does not need to be defined in the HTML code. Pseudo-elements are distinguished by a double colon (::), which was introduced in CSS3. Note that all the pseudo-elements that were introduced before CSS3 used a single colon (:), similar to the pseudo-class syntax.

The following code snippet will select all the generated content defined by the content style property that appears after the <p> element:

The HTML code is as follows:

<p>Paragraph content goes here</p>

The CSS code is as follows:

p::after {
  content: " 'I come after a paragraph' ";
  color: blue; background-color: yellow;
}

The output will be:

Paragraph content goes here 'I come after a paragraph'

The following table lists the pseudo-elements:

Tip

Although you can have the same behavior programmatically by adding classes to your HTML code using JavaScript, it is easier to add pseudo-classes and pseudo-elements to your selectors; moreover, it gives you cleaner code.

主站蜘蛛池模板: 车致| 龙胜| 思南县| 蓝山县| 平利县| 和田县| 河津市| 中牟县| 昭通市| 绥阳县| 北海市| 广河县| 靖边县| 梅河口市| 昌乐县| 洞头县| 任丘市| 安国市| 霍城县| 洛南县| 湖北省| 文水县| 日土县| 卢湾区| 屯昌县| 巴马| 西峡县| 手游| 衡南县| 开化县| 南投市| 胶州市| 桦甸市| 城口县| 鸡泽县| 织金县| 任丘市| 广南县| 建昌县| 商城县| 铁力市|