Attribute Selectors in CSS

Here we will learn about the CSS attribute selectors in CSS. This is used in advanced cases of creating powerful ways of HTML styling. This is quite easy if you know about the basic selectors in CSS. You can add a selector using a value between a pair of brackets. Let us go through them in detail.

[attribute] selector

This is a simple way of using title attributes for styling elements of the texts.

For example

<head>
<title>CSS</title>
<style>
    [title] {
        color:green;
    }
</style>
</head>
<body>
    <h1 title="heading">Codespeedy</h1>
    <p title="paragraph">Coding is fun.</p>
</body>

[attribute=”value”] selector

Here we need an added value to the attribute by a = operator to match with the elements for styling.

<head>
<title>CSS</title>
<style>
    input[type="text"] {
        border:1px black;
    }
  
</style>
</head>
<body>
    <form>
        <input type="text">   
       <p> write something in box </p>
    </form>
</body>

[attribute~=”value”] Selector

It matches the space-separated values to match the similar type of specified values.

For example:

<head>
<title>CSS</title>
<style>
    [class~="code"] {
    color: #fff;
        
    }
</style>
</head>
<body>
    <p class="code">Codespeedy.</p>
</body>

[attribute*=”value”] Selector

This is specified with *= operator to match all the elements with the given value.

<head>
<title>CSS</title>
<style>
    [class*="code"] {
        color: #fff;
        background: black;
    }
</style>
</head>
<body>
    <p class="code">Codespeedy.</p>  
</body>

[attribute|=”value”] Selector

Here |= operator is used to match any element whose attribute has a similar type of specified value.

<head> 
<title>CSS</title>
 <style>
 p[lang|= code]
 { color: #fff; 
background: red; } 
</style>
</head>
 <body>
 <p lang="code">Codespeedy.</p>
 </body>

These were some advanced topics related to attribute selectors in CSS. To know more about its properties, you should be aware of the basic concept of selectors in CSS.

Leave a Reply

Your email address will not be published.