In this sixth course, we’ll plunge deeper into the CSS world, we will take a deeper look at the CSS selectors with ID and Class.
Previously, we’ve learn the basic of CSS and how to insert a style sheet inside a web page.
The selectors are the first part of a CSS command. So far, we’ve been using HTML tags as selector (EX: p, h1, etc.). Today we will see how to apply our CSS command to a class or to a specific ID.
For today’s course, we will look at two new HTML tags, the “div” and the “span” tags. Both tags are empty container that will allow us to regroup code and format it to our liking. In later course, the will be used to create column, header, footer and menu. The only difference between both tag is the “div” tag will group all element inside an inside a block, and the “span” tag will group element inline.
The ID!
In CSS, the “ID” is a way to identify a unique element in a web page. It is important that the assigned id only appears once in a web page. A practical use for ids would be to define footer, header or any part of code that are unique. To assign a id to a html tag, we simply use the attribute id like so:
<div id="header"></div>
And in our CSS code, to set a style directly to the id, we will use the hash character (#) like the following example:
#header { color:blue; }
Make way for the CLASS!
A CSS class is similar to the id, but compare to id, a class can be used multiple times in a web page. So we could create a class to give show an alert on screen to our users or to emphasize on certain part of our text, here an example of a class in HTML and in CSS:
.alert { color:red; font-weight:bold; }
And in HTML:
<p>Let’s have <span class=”alert”>fun</span> with my new alert <span class=”alert”>message</span></p>
The class will be defined by a dot (.) in the CSS document and with the class attribute in HTML.
Now to finish up, let’s mix our class and id together for some interesting result, since in CSS, you can place more than one consecutive selector.
<div id="wrapper"> <p>This is a first paragraphe <span class="alert">in</span> my wrapper id.</p> </div> <p>This is a second paragraphe <span class="alert">outside</span> my wrapper id.</p>
With this HTML code, let’s add our CSS with a twist:
#wrapper{ background-color :lighegrey; } #wrapper .alert{ background-color :cyan; color:red; } P { color:indigo; }
The twist here is where I wrote “#wrapper .alert”, this would tell the browser that only the class alert within the id wrapper will change colors; the other class alert will not be influence.
That all for today and again you can watch the video lesson for added value on this tutorial.
Next article we will see how to create a HTML document with two columns.
Leave a Reply