Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Use Selectors to Style HTML Elements

    Tyler ClarkTyler Clark

    CSS gives us the ability to work with many different types of selectors to target and style HTML. In this lesson we will understand how to use classes, ids, elements, attributes, and the universal selector.

    cssCSS
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 There are many different ways you can target HTML to style. Here in the browser, I'm running some basic unstyled HTML, which is also shown here. Let's use CSS to target and style this h1 tag that holds my name.

    00:17 The first way we can target and style the h1 is by using a type selector. Type selectors match the provided node. All h1 elements within the scope of this CSS will have a blue color.

    00:31 We could affect not only this one h1, but every element by using the universal selector. This accomplishes our goal, but it's not very efficient, because the browser will have to apply it to many nodes.

    00:43 Instead, let's go ahead and add a class attribute to our h1, and we'll give it a string of name. Instead of our styles, we'll change this universal selector to .name and refresh. As you can see, now we're only targeting our one h1. This is the third type of selector, the class selector. This will match in style and every element that has the class attribute of name.

    01:08 When we are targeting classes, we use the dot in front of the providing class name. There is also the ID selector, which is also an attribute called ID on the HTML element. However, we don't target IDs with the dot, but with the #. Our element is still blue. Let's go ahead and remove this ID attribute and replace it with data-name = "name".

    01:36 Instead of our CSS, we'll do data-name = "name". If we save this and refresh, we'll see that we're still blue. While there are specific methods for targeting class and ID element attributes, other attributes provided to HTML elements can be targeted as well by copying the attribute and placing it within square brackets. This is called using the attribute selector.

    Discuss

    Discuss