CSSHTML

Targeting CSS Based on Attribute Values

By May 8, 2018 No Comments

There are so many different methods when targeting elements in CSS.  The most widely used are the class “.” and id “#” selectors.  Sometimes you may need to target based on an attribute when other elements are not available.

Here’s some examples of how to target on attribute values:

Target on Input Name

<input class="form-control" name="inputOne"/>
<style>
    input[name="inputOne"]{
        border-color:red;
    }
</style>

 

Target on Input Name Starts With

<input class="form-control" name="randomInputOne"/>
<input class="form-control mt-3" name="randomInputTwo"/>
<style>
    input[name^="random"]{
        border-color:blue;
    }
</style>

 

Target on Input Name Ends With

<input class="form-control" name="threeRandomInput"/>
<input class="form-control mt-3" name="fourRandomInput"/>
<style>
    input[name$="Input"]{
        border-color:green;
    }
</style>

 

Target on Input Name Includes

<input class="form-control" name="nameIncludesThis"/>
<input class="form-control mt-3" name="otherIncludesThat"/>
<style>
    input[name*="Includes"]{
        border-color:orange;
    }
</style>

 

Target a href element

<a href="https://www.prodjex.com">This is a link.</a>
<style>
    a[href="https://www.prodjex.com"]{
        color:brown;
    }
</style>

 

Target data-value element

<a href="https://www.prodjex.com/web-development-blog/" data-value="webLink">This is another link.</a>
<style>
    [data-value="webLink"]{
        color:purple;
    }
</style>

 

View demos of all these examples in action here.

Leave a Reply