Cascading Style Sheets (CSS)
Introduction
- CSS is the language we use to style an HTML document.
- CSS describes how HTML elements should be displayed.
- CSS saves a lot of work. It can control the layout of multiple web pages all at once.
CSS Syntax
- A CSS rule consists of a selector and a declaration block.
CSS Selector
CSS selectors are used to “find” (or select) the HTML elements you want to style.
- The CSS element selector:- The element selector selects HTML elements based on the element name
h1{
text-align: center;
}
2. The CSS id selector:-
The id selector uses the id attribute of an HTML element to select a specific element.
The id of an element is unique within a page, so the id selector is used to select one unique element!
To select an element with a specific id, write a hash (#) character, followed by the id of the element.
#studentForm{
padding : 10px;
}
3. The CSS class Selector:-
The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the class name.
.container{
margin: 10px;
padding: 10px;
}p.center {
text-align: center;
background-color: red;
color: white;
}
Note: An id name and class name cannot start with a number!
There are 3 ways to add CSS files to your webpages
- External CSS
- Internal CSS
- Inline CSS
External CSS
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>I am Heading</h1><p>I am a Paragraph.</p>
</body>
</html>
style.css
h1 {
color: red;
margin-left: 20px;
}p {
background-color: black;
color: white;
}
Internal CSS
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Inline CSS
<!DOCTYPE html>
<html>
<body>
<h1 style="color:blue;text-align:center;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>
</body>
</html>
Cascading Order
What style will be used when there is more than one style specified for an HTML element?
All the styles in a page will “cascade” into a new “virtual” style sheet by the following rules, where number one has the highest priority:
- Inline style (inside an HTML element)
- External and internal style sheets (in the head section)
- Browser default
So, an inline style has the highest priority and will override external and internal styles and browser defaults.