CSS Introduction
What is CSS?
CSS stands for Cascading Style Sheets and is the language used to apply styles to a web page such as color, fonts, margins, padding and height/width.
The use of CSS is quite versatile as it can also change the layout of a whole page. This can be achieved in a various ways: e.g. floating elements, using flexbox and the css grid.
The CSS syntax
Let's break it down:
<p> {color: red;}
The <p> is called Selector as it selects the element to be styled.
color: is the property.
red; is the value.
How do we insert CSS in HTML?
There are multiple ways:
1. Use the inline style attribute inside the opening tag of the targetted element - see the example below:
This element's color is red.
The result:
This element's color is red.
2. Create a separate CSS stylesheet and insert the stylesheet link. Open you editor, give your file a name and save it as a CSS file. Once you do that then insert the link into the head of your HTML document as depicted below:
The CSS link
The stylesheet should be inserted as a link between the head tags.
3. Insert the CSS code between the <style> </style> tags inside the HTML code as per the example below:
The CSS link
The style properties (e.g. color: red;) should be inserted between the style tags.
Selectors: The Class and id
In CSS in order to style an element you must first select it and in order to do this you will need to target it using one of the two selectors below.
1. The Class Selector
The Class selector is used to select multiple elements that we want to apply the style changes.
You insert inside the opening tag of the elements you wish to change the attribute class="" and you can use any name you want. It is good practice to use a short descriptive name.
Inside the <style> </style> tags type the name you have given to the class starting with a dot (.)
For example:
The Class selector
The first paragraph
The second paragraph
The third paragraph
The result:
The first paragraph
The second paragraph
The third paragraph
2. The id Selector
The id selector is used to selct a specific element that we want to style.
Insert inside the opening tag of the targeted element the attribute id="" and give it a name of your choice. As with the Class selector make sure that you use a short and descriptive name.
Now, between the <style> </style> tags type the name you have given to the id starting with a hash (#)
For example:
The Class selector
The first paragraph
The second paragraph
The third paragraph
The result:
The first paragraph
The second paragraph
The third paragraph