Attribute selectors

In addition to element selectors, we can also use their attribute selectors. For example, we have several input fields on a web page, and we only need to color the text fields red. In this case, we can just check the value of the attribute type: if it has a value text, then this is a text field, and accordingly it should be colored red. The style definition in this case would look like this:

input[type="text"]{
  border: 2px solid red;
}

After the element in square brackets comes the attribute and its value. That is, in this case, we say that for the text field, you need to set a red border of 2 pixels with a thick solid line.

For example:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attribute selectors in CSS3</title>
    <style>
        input[type="text"] {
            border: 2px solid red;
        }
    </style>
</head>

<body>
    <p><input type="text" id="login" /></p>
    <p><input type="password" id="password" /></p>
    <input type="submit" value="Send" />
</body>

</html>


Attribute selectors can be applied not only to elements, but also to classes and identifiers. For example:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attribute selectors in CSS3</title>
    <style>
        .link[href="http://apple.com"] {
            color: red;
        }
    </style>
</head>

<body>
    <a class="link" href="http://microsoft.com">Microsoft</a> |
    <a class="link" href="https://google.com">Google</a> |
    <a class="link" href="http://apple.com">Apple</a>
</body>

</html>


Special characters allow you to specify the meaning of attributes. For example, the ^ symbol allows you to select all attributes that start with a specific text. For example, we need to select all links that use the https protocol, that is, the link must begin with “https://”. In this case, you can apply the following selector:

a[href^="https://"]{
    color: red;
}

If the attribute value must have some text at the end, then the $ symbol is used for validation. For example, we need to select all images in jpg format. In this case, we can check if the attribute value ends with srcthe text “.jpg”:

img[src$=".jpg"]{
    width: 100px
}

And one more character “*” (asterisk) allows you to select all elements with attributes that have a certain text in their value (it doesn’t matter where – at the beginning, middle or end):

a[href*="microsoft"]{
    color: red;
}

This attribute will select all links that have the text “microsoft” in their address.