Cascading Stylesheet (CSS) is a stylesheet language. Stylesheet languages like CSS describe the presentation of a document.
CSS is mostly used to style web pages written in HTML. All aspects of presenting an HTML document can be controlled using CSS including font, color, size, spacing, animations etc.
CSS syntax is optimized for declaring sets of styles you want to apply on HTML elements.
A CSS declaration consist of property and value pairs:
CSS declarations are case-insensitive.
color: blue /*set font color to blue*/
font-family: helvetica /*set font family to helvetica*/
border-width: 2px /*set width of border equal to 2 px */
CSS Declarations can be grouped into blocks, delimited by opening '{' and closing '}' braces. Declarations inside a block are separated by a semi-colon.
A Declaration block is not very useful when used alone (without CSS Selectors) as the styles defined inside it will be applied to the whole document.
{
font-family : helvetica;
font-size : 12px;
}
Above example sets the style for the whole document.
We can target a specific element or group of elements using CSS Selector and can apply a set of styles to it using declaration block as shown below.
p {
font-family : helvetica;
font-size : 12px;
}
Here p is a CSS Selector that selects all paragraph in the document and apply properties defined inside declaration block. We will discuss different types of CSS Selectors in another article.
CSS Selector along with declaration block forms the CSS Ruleset.
Using CSS ruleset we can easily set the style of all elements in a document according to our requirement.
CSS can be added in three different ways :
CSS can be added inline in HTML elements using style attribute.
<p style="color : blue; font-family : helvetica"> Paragraph goes here...
</p>
In above example, we are using CSS to change paragraph's font color to blue and font family to Helvetica.
Instead of adding CSS inline to each HTML element, we can add CSS using <style> tag in <head> section. We can make use of CSS Selectors to apply specific styles to different elements.
<head >
...
<style>
p {
color : blue;
font-family : helvetica;
}
</style >
...
</head>
Here p is a selector which selects all p elements in the document. There are CSS selectors which are more specific and allow us to select a particular paragraph instead of selecting all of them. We will discuss CSS selectors in detail in another article.
We can also write CSS in a separate CSS file(.css). CSS files defined in this way are added to the HTML document using <link> tag in <head> section.
index.html <head>
...
<link rel="stylesheet" type="text/css" href="./css/mystyle.css" />
</head>
p {
color : blue;
font-family : helvetica;
}
Link tag is used here to include an external CSS document. The attributes used are:
In the next article, we will explore different CSS Selectors that can be used to select elements in a document.