CSS Selectors – How to select elements for styling

CSS

0 Comments

Selectors in CSS allow us to select elements, so we can style them.

In the previous button styling example, we learned how to style elements by class. However, that isn't the only way.

Basic CSS Selectors

HTML we'll be using for this example

<p id="myId" class="myClass">This is a paragraph</p>

CSS

/* Select by HTML tag */
p {
    font-size: 14px;
}

/* Select by class (.) */
.myClass {
    padding: 10px;
}

/* Select by HTML id (#) */
#myId {
    margin-bottom: 20px;
}
Select by HTML tag (Line 2)
Simply use the HTML tag name as the selector (ul, h1, a, etc..).
Select by class (Line 7)
Add a period in front of the class name.
Select by HTML id (Line 12)
Add a # in front of the HTML id. Remember you can add a custom id attribute to any HTML tag (but the id should be unique to that page).

Intermediate CSS Selectors

HTML for example

<ul id="menu">
	<li>
        <a href="/html/">HTML</a>
    </li>
	<li>
        <a href="/css/">CSS</a>
    </li>
</ul>

<input type="button" value="Click me">

CSS

/* Descendent selector: Select elements that are somewhere inside another element */
#menu a {
    color: white;
}

/* Child selector: Select child based on its immediate parent */
li > a {
    margin-right: 20px;
}

/* Attribute selector: Select by HTML attribute */
input[type="button"] {
    background-color: blue;
}
Descendent selector (Line 2)
Let's you select elements that are somewhere inside another element.
#menu a selects all <a> tags that are somewhere inside the ul with id="menu". Notice that the ul is not the immediate parent of the <a> (li is). However, this selector doesn't care.
Child selector (Line 7)
Select a child element based on its immediate parent.
li > a selects all <a> tags that have li as their immediate parent. If we instead put ul > a, the <a> would not be selected because <a> doesn't have ul as its immediate parent (li is its parent).
Attribute selector (Line 12)
input[type="button"] selects all input tags with the attribute type="button".

Leave a Comment