CSS Selectors


Collapse Content

In CSS, there are many ways to specify the items you want to apply a style to.

HTML Elements

You can specify a specific HTML element, such as p, h1, or table.

p { color: green; }

The above rule sets all paragraphs to a green color.

h1 { font-size: 4em; }

This sets all <h1> elements to 4em (a large size!).

Classes

Often you want to customize the look of specific paragraphs without changing every paragraph. For example, in the online store, you may want to emphasize certain paragraphs more than other ones. Using p as a selector would select All paragraphs, but we need a way to only select the elements we want.

You can do this with the class attributes. Mark the HTML element you want to customize with a class:

<p class="emphasis">You will be able to buy great things here.</p>

This is similar to inserting an inline style in Where is CSS, but this time we'll move the actual CSS outside the HTML.

Next, create a CSS rule for the class emphasis. CSS class selectors are marked with a period, as in .className:

.emphasis {
  color: darkgreen;
  font-style: italic;     
}

This will make your previous paragraph look like this:

You will be able to buy great things here.

ID's

Sometimes you just want to customize a single item. In such a case you don't need a class, and can use an ID. An ID can only be used by one item on a page, and each item can have at most one ID.

Here's an example of an ID attribute in HTML:

<p id="unique">This paragraph appears once.</p>

To select an ID in CSS, you add a # before the name of the ID:

#unique {
  color: purple; 
}

This paragraph appears once


Let's add a single picture to the online store and customize it. We can use the following image, located over here:

Add the image below the first paragraph:

<p> You will be able to buy great things on this store. </p>

<img src="https://s3.amazonaws.com/learneroo-images/samples/cow-grass-small.jpg">

Since this will be the only image of this type on the page, we'll add an ID to it to style it:

<img src="https://s3.amazonaws.com/learneroo-images/samples/cow-grass-small.jpg" id="sample-pic">

Now let's add some CSS to select that ID

Next let's add some CSS to style the image. Let's give the image some space by adding a 15px margin on all sides:

margin: 15px;

Here's the CSS with the selector and statement:

#sample-pic {
  margin:15px;
}

Want to learn and practice CSS selectors in more depth? See this interactive CSS selector tutorial.

Challenge

Write the selector to select the id sample-pic. (Don't include the {} braces.)

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us
Sign in or email us at [email protected]