CSS Selectors: Type Selectors

Below are the CSS Type selectors we are going to learn.

 # The Element Selector
# The Class Selector
# The ID Selector
# Grouping Selectors

Below is a sample HTML file with some tags

<html>
<head></head>
<body>
<h1> This is header </h1>
<p class=”info”>Some paragraph class info</p>
<p id=”warning”>Dont do this! Some paragraph id warning</p>
<p class=”info”>Some other paragraph class info — really?</p>
<p class=”primary”>Basic texts. Some paragraph class primary</p>
</body>
</html>

#The Element Selector (element name)

The h1, body and p are all elements. Do you remember how elements are selected and styled? Below is an example:

h1 {
background-color: blue;
}

In the code above, the h1 element is selected and styled. h1 could be substituted for any other HTML element.

#The Class Selector (. followed by class name)

You add a . before the class name. Then style the selected class whichever way you like. The single declaration color: green will now be applied to every element with the class name, info.

 <p class=”info”>Some paragraph class info</p>
<p class=”info”>Some other paragraph class info — really?</p>
<p class=”primary”>Basic texts. Some paragraph class primary</p>
/* css for a class selector for above class selectors*/.info {
color: green;
}

#The ID Selector (# followed by class id)
Unlike classes that may be applied to as many elements as possible, an ID is specific to a single element. You add the pound sign, # before the ID name.

 #warning {
color: red;
}

#Grouping Selector (comma separation between multiple separators)

If you want to apply the same CSS declaration to 2 or more different classes?
For instance, you may want the elements with class names, info and primary to have the same background-color of red.

You may think of it like this. Yes, that works.

.info {
background-color: red;
}
.primary {
background-color: red;
}

But there is a better way to group elements in CSS. Take a look:

 .info, .primary {
background-color: red;
}

Just add a comma , and you can group multiple selectors. As seen above.

Conclusions:-
# Use type selectors when all or most instances of an HTML element need to be styled in the same way.
# Use classes to select elements that are more specific, reusable, and flexible than type selectors.
# ID values can only be used once per page, so stick to using them for unique styles and global elements that are not repeated.

References:-

The Complete Advanced Guide to CSS — Learn Interactively (educative.io)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store