Cascading Style Sheet - CSS
Introduction
CSS is the language we use to style a Web page.
What is CSS?
• CSS stands for Cascading Style Sheets
• CSS describes how HTML elements are to be displayed on screen, paper,
or in other media
• CSS saves a lot of work. It can control the layout of multiple web pages
all at once
• External stylesheets are stored in CSS files
Why Use CSS?
CSS is used to define styles for your web pages, including the design, layout
and variations in display for different devices and screen sizes.
What are the advantages of CSS?
The following are the advantages of CSS −
• CSS saves time − You can write CSS once and then reuse the same sheet
in multiple HTML pages. You can define a style for each HTML element
and apply it to as many Web pages as you want.
• Easy maintenance − To make a global change, simply change the style,
and all elements in all the web pages will be updated automatically.
• Global web standards − Now HTML attributes are being deprecated and
it is being recommended to use CSS. So, it's a good idea to start using
CSS in all the HTML pages to make them compatible with future
browsers.
• Platform Independence − The Script offer consistent platform
independence and can support latest browsers as well.
CSS Syntax
A CSS rule consists of a selector and a declaration block.
The selector points to the HTML element you want to style.
The declaration block contains one or more declarations separated by
semicolons.
Each declaration includes a CSS property name and a value, separated by a
colon.
Multiple CSS declarations are separated with semicolons, and declaration
blocks are surrounded by curly braces.
[Link]
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
p{
font-family: verdana;
font-size: 20px;
}
</style>
</head>
<body>
<h1>My First CSS Example</h1>
<p>This is a paragraph.</p>
</body>
</html>
Output:
Example Explained
• body is a selector in CSS (it points to the HTML element you want to
style: <body>).
• h1 is a selector in CSS (it points to the HTML element you want to style:
<h1>).
• p is a selector in CSS (it points to the HTML element you want to style:
<p>).
• background-color is a property, and lightblue is the property value
• color is a property, and white is the property value
• text-align is a property, and center is the property value
• font-family is a property, and verdana is the property value
• font-size is a property, and 20px is the property value
What are the different types of CSS?
There are three types of CSS which are given below:
• Inline - by using the style attribute inside HTML elements
• Internal - by using a <style> element in the <head> section
• External - by using a <link> element to link to an external CSS file
Inline CSS
An inline CSS is used to apply a unique style to a single HTML element.
An inline CSS uses the style attribute of an HTML element.
<!DOCTYPE html>
<html>
<body>
<h1 style="color:blue;">A Blue Heading</h1>
<p style="color:red;">A red paragraph.</p>
</body>
</html>
Internal CSS
An internal CSS is used to define a style for a single HTML page.
An internal CSS is defined in the <head> section of an HTML page, within
a <style> element.
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
External CSS
An external style sheet is used to define the style for many HTML pages.
"[Link]":
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p{
color: red;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
CSS Comments
- Comments are used to explain the code, and may help when you edit the
source code at a later date.
- Comments are ignored by browsers.
- A CSS comment is placed inside the <style> element, and starts
with /* and ends with */
<style>
/* This is a single-line comment */
p{
color: red;
}
</style>
You can add comments wherever you want in the code:
<style>
p{
color: red; /* Set text color to red */
}
</style>
Comments can also span multiple lines:
<style>
/* This is a multi-line comment
This is a multi-line comment
This is a multi-line comment */
p{
color: red;
}
</style>
Combination of HTML and CSS comments
<!DOCTYPE html>
<html>
<head>
<style>
p{
color: red; /* Set text color to red */
}
</style>
</head>
<body>
<h2>My Heading</h2>
<!-- These paragraphs will be red
This is HTML comments -->
<p>Hello World!</p>
<p>This paragraph is styled with CSS.</p>
<p>CSS comments are not shown in the output.</p>
</body>
</html>
CSS Selectors
CSS selectors are used to "find" (or select) the HTML elements you want to
style.
1. The CSS element Selector
The element selector selects HTML elements based on the element name.
Here, all <p> elements on the page will be center-aligned, with a red text
color:
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.
The CSS rule below will be applied to the HTML element with id=”para1”:
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.
In this example, all HTML elements with class=”center” will be red and
center-aligned:
In this example only <p> elements with class="center" will be red and center-
aligned:
HTML elements can also refer to more than one class.
In this example, the <p> element will be styled according to class=”center”
and class=”large”:
4. The CSS Universal Selector
The universal selector (*) selects all HTML elements on the page.
The CSS rule below will affect every HTML element on the page:
5. The CSS Grouping Selector
The grouping selector selects all the HTML elements with the same style
definitions.
Look at the following CSS code (the h1, h2, and p elements have the same style
definitions):
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p{
text-align: center;
color: red;
}
It will be better to group the selectors, to minimize the code.
To group selectors, separate each selector with a comma.
CSS Properties
A CSS property assign a style or behavior to an HTML element.
Property List
CSS supports more than 200 CSS properties. Here’s a complete list:
Property Description
background-color Sets the background color of an element
Background color with div {
Opacity/Transparency background-color: green;
opacity: 0.3;
}
div {
Transparency using background: rgba(0, 128, 0, 0.3) /* Green
RGBA background with 30% opacity */
}
background-image Sets the background image for an element
background-repeat Sets how a background image will be repeated
body {
background-image: url("gradient_bg.png");
background-repeat: repeat-x;
}
Note: To repeat an image vertically, set
background-repeat: repeat-y;
background-attachment Specifies whether the background image should scroll or
be fixed.
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: fixed;
}
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: scroll;
}
background-size Specify the size of a background-image with “auto” and
in pixels.
#example1 {
background: url([Link]);
background-repeat: no-repeat;
background-size: auto;
}
#example2 {
background: url([Link]);
background-repeat: no-repeat;
background-size: 300px 100px;
}
background-position left top, left center, left bottom, right top, right center,
right bottom, center top, center center, center bottom
background body {
background-color: #ffffff;
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
You can use the shorthand property background in one
declaration:
body {
background: #ffffff url("img_tree.png") no-repeat right
top;
}
color Specifies the color of text in an element
Text Color - The color property is used to set the color of
the text. The color is specified by:
• a color name - like "red"
• a HEX value - like "#ff0000"
• an RGB value - like "rgb(255,0,0)"
text-align Specifies the horizontal alignment of text. A text can be
left or right aligned, centered, or justified.
• text-align-last • The text-align-last property specifies how to align
• direction the last line of a text.
• unicode-bidi • The direction and unicode-bidi properties can be
used to change the text direction of an element. p {
• vertical-align direction: rtl;
unicode-bidi: bidi-override;
}
• The vertical-align property sets the vertical
alignment of an element. (Values are baseline, text-top,
text-bottom, sub, super)
text-transform Controls the capitalization of text
text-decoration Sets all the text-decoration properties in one declaration
The text-decoration property is a shorthand property for:
• text-decoration-line (required)
• text-decoration-color (optional)
• text-decoration-style (optional)
• text-decoration-thickness (optional)
text-transform This property is used to specify uppercase and lowercase
letters or capitalize the first letter of each word.
text-indent Used to specify the indentation of the first line of a text
p {
text-indent: 50px;
}
letter-spacing Specifies the space between characters in a text
Eg. h1{letter-spacing:5px;}
Eg. h2 {letter-spacing: -2px;}
text-indent Specifies the indentation of the first line in a text-block
Eg. p{text-indent:50px;}
line-height Specifies the space between line
Eg. [Link] {
line-height: 0.8;
}
[Link] {
line-height: 1.8;
}
word-spacing Specifies the space between words in a text
Eg. [Link] {
word-spacing: 10px;
}
[Link] {
word-spacing: -2px;
}
text-shadow Specify the horizontal shadow and the vertical shadow.
h1 {
text-shadow: 2px 2px;
}
h1 {
text-shadow: 2px 2px red;
}
h1 {
text-shadow: 2px 2px 5px red;
}
h1 {
text-shadow: 0 0 3px #ff0000, 0 0 5px #0000ff;
}
h1 {
color: white;
text-shadow: 1px 1px 2px black, 0 0 25px blue, 0
0 5px darkblue;
}
font-family Specifies the font of the text
Eg. .p1 {
font-family: "Times New Roman", Times, serif;
}
Google font <head>
<link rel="stylesheet" href="[Link]
[Link]/css?family=Sofia">
<style>
body {
font-family: "Sofia", sans-serif;
}
</style>
</head>
font-style Specifies italic text (property values: normal, italic,
oblique)
font-weight Specifies the weight of a font (property values: normal,
lighter, bold, 900)
font-variant Specifies where or not a text should be displayed in a
small-caps font. (property values: normal, small-caps)
font-size Sets the size of the text. The text size can be set with a
px(pixel) unit, em(1em=16px) unit, percent unit, etc.
Styling Links
Links can be styled with any CSS property (e.g. color, font-family, background,
etc.)
In addition, links can be styled differently depending on what state they are in:
The four links states are:
a:link – a normal, unvisited link
a:visited – a link the user has visited
a:hover – a link when the user mouses over it
a:active – a link the moment it is clicked
- When setting the style for several link states, there are some order rules:
a:hover MUST come after a:link and a:visited
a:active MUST come after a:hover
- The text-decoration property is mostly used to remove underlines from links.
E.g. a:link{text-decoration: none;} a:hover{text-decoration: underline;}
- The background-color property can be used to specify a background color for
links.
E.g. a:link{background-color:yellow;} a:hover{background-color:lightgreen;}
CSS Lists Properties
The CSS list properties allow you to:
• Set different list item markers for ordered lists
• Set different list item markers for unordered lists
• Set an image as the list item marker
• Add background colors to lists and list items
Different List Item Markers
Property Description
list-style-type Specifies the type of list item maker
(Property values: circle, square, upper-roman, lower-alpha)
list-style-image Specifies an image as the list item marker
E.g. ul{list-style-image: url(‘[Link]’);}
list-style-position Specifies the position of the list-item markers (bullet points).
(Property values: outside, inside)
List shorthand property
ul {
list-style: square inside url("[Link]");
}
instead of
ul {
list-style-type: square;
list-style-image: url("[Link]");
list-style-position: inside;
}
CSS Tables
Table Borders
To specify table borders in CSS, use
the border property.
The example below specifies a solid border for <table>, <th>, and <td>
elements:
You can change the table width and border style as follow:
The border-collapse property sets whether the table borders should be collapsed
into a single border.
Table Size (Table Width and Height)
The width and height of a table are defined by the width and height properties.
Output will displayed as follow:
Table Alignment (Horizontal Alignment)
- The text-align property sets the horizontal alignment (like left, right, or center) of
the content in <th> or <td>.
- By default, the content of <th> elements are center-aligned and the content of
<td> elements are left-aligned.
Output will displayed as follow:
Vertical Alignment
- The vertical-align property sets the vertical alignment (like top, bottom, or middle) of the
content in <th> or <td>.
- By default, the vertical alignment of the content in a table is middle (for both <th> and
<td> elements).
Output will be displayed as follow:
Table Style
Table Padding
To control the space between the border and the content in a table, use
the padding property on <td> and <th> elements:
Horizontal Dividers
Add the border-bottom property to <th> and <td> for horizontal dividers:
Hoverable Table
Try it yourself:
Striped Tables
For zebra-striped tables, use the nth-child() selector and add a background-color to all
even (or odd) table rows:
Try it yourself:
Table Color
You can specify the background color and text color of <th> and <td> elements.
CSS Border Style
The border-style property specifies what kind of border to display.
The following values are allowed:
• dotted - Defines a dotted border
• dashed - Defines a dashed border
• solid - Defines a solid border
• double - Defines a double border
• groove - Defines a 3D grooved border. The effect depends on the border-color value
• ridge - Defines a 3D ridged border. The effect depends on the border-color value
• inset - Defines a 3D inset border. The effect depends on the border-color value
• outset - Defines a 3D outset border. The effect depends on the border-color value
• none - Defines no border
• hidden - Defines a hidden border
The border-style property can have from one to four values (for the top border, right
border, bottom border, and the left border).
Demonstration of the different border style:
Try it yourself
CSS Border Width
The border-width property specifies the width of the four borders.
The width can be set as a specific size (in px, pt, cm, em, etc) or by using one of the three
pre-defined values: thin, medium, or thick.
The border-width property can have from one to four values (for the top border, right
border, bottom border, and the left border).
CSS Border Color
The border-color property is used to set the color of the four borders.
The color can be set by:
• name - specify a color name, like "red"
• HEX - specify a HEX value, like "#ff0000"
• RGB - specify a RGB value, like "rgb(255,0,0)"
• HSL - specify a HSL value, like "hsl(0, 100%, 50%)"
• transparent
CSS Border - Shorthand Property
The border property is a shorthand property for the following individual border
properties:
• border-width
• border-style (required)
• border-color
For example:
p{
border: 5px solid red;
}
p{
border-left: 6px solid red;
}
p{
border-bottom: 6px solid red;
}
CSS Rounded Borders
The border-radius property is used to add rounded borders to an element:
CSS Margins
The CSS margin properties are used to create space around elements, outside of any
defined borders.
With CSS, you have full control over the margins. There are properties for setting the
margin for each side of an element (top, right, bottom, and left).
Margin - Individual Sides
CSS has properties for specifying the margin for each side of an element:
• margin-top
• margin-right
• margin-bottom
• margin-left
All the margin properties can have the following values:
• auto - the browser calculates the margin
• length - specifies a margin in px, pt, cm, etc.
• % - specifies a margin in % of the width of the containing element
• inherit - specifies that the margin should be inherited from the parent element
Note: Negative values are allowed.
Margin - Shorthand Property
The margin property is a shorthand property for the following individual margin
properties:
• margin-top
• margin-right
• margin-bottom
• margin-left
If the margin property has four values:
• margin: 25px 50px 75px 100px;
o top margin is 25px
o right margin is 50px
o bottom margin is 75px
o left margin is 100px
If the margin property has three values:
• margin: 25px 50px 75px;
o top margin is 25px
o right and left margins are 50px
o bottom margin is 75px
If the margin property has two values:
• margin: 25px 50px;
o top and bottom margins are 25px
o right and left margins are 50px
If the margin property has one value:
• margin: 25px;
o all four margins are 25px
The auto Value
You can set the margin property to auto to horizontally center the element within its
container.
The element will then take up the specified width, and the remaining space will be split
equally between the left and right margins.
For example:
Use margin: auto;
Use of the inherit value;
CSS Padding
The CSS padding properties are used to generate space around an element's content,
inside of any defined borders.
With CSS, you have full control over the padding. There are properties for setting the
padding for each side of an element (top, right, bottom, and left).
Padding - Individual Sides
CSS has properties for specifying the padding for each side of an element:
• padding-top
• padding-right
• padding-bottom
• padding-left
All the padding properties can have the following values:
• length - specifies a padding in px, pt, cm, etc.
• % - specifies a padding in % of the width of the containing element
• inherit - specifies that the padding should be inherited from the parent element
Note: Negative values are not allowed.
For example:
Padding - Shorthand Property
To shorten the code, it is possible to specify all the padding properties in one property.
The padding property is a shorthand property for the following individual padding
properties:
• padding-top
• padding-right
• padding-bottom
• padding-left
If the padding property has four values:
• padding: 25px 50px 75px 100px;
o top padding is 25px
o right padding is 50px
o bottom padding is 75px
o left padding is 100px
If the padding property has three values:
• padding: 25px 50px 75px;
o top padding is 25px
o right and left paddings are 50px
o bottom padding is 75px
If the padding property has two values:
• padding: 25px 50px;
o top and bottom paddings are 25px
o right and left paddings are 50px
If the padding property has one value:
• padding: 25px;
o all four paddings are 25px
Padding and Element Width
For example:
CSS Height and Width
The height and width properties are used to set the height and width of an element.
The height and width properties may have the following values:
• auto - This is default. The browser calculates the height and width
• length - Defines the height/width in px, cm, etc.
• % - Defines the height/width in percent of the containing block
• initial - Sets the height/width to its default value
• inherit - The height/width will be inherited from its parent value
Example
div { div {
height: 200px; height: 100px;
width: 50%; width: 500px;
background- background-
color: powderblue; color: powderblue;
} }
Setting max-width
The max-width property is used to set the maximum width of an element.
The max-width can be specified in length values, like px, cm, etc., or in percent (%) of
the containing block, or set to none (this is default. Means that there is no maximum
width).
Example
This <div> element has a height of 100 pixels and a max-width of 500 pixels:
div {
max-
width: 500px;
height: 100px;
background-
color: powderblue
;
}
CSS Box Model
All HTML elements can be considered as boxes.
In CSS, the term "box model" is used when talking about design and layout.
The CSS box model is essentially a box that wraps around every HTML element. It
consists of: margins, borders, padding, and the actual content. The image below illustrates
the box model:
Explanation of the different parts:
• Content - The content of the box, where text and images appear
• Padding - Clears an area around the content. The padding is transparent
• Border - A border that goes around the padding and content
• Margin - Clears an area outside the border. The margin is transparent
The box model allows us to add a border around elements, and to define space between
elements.
Demonstration of Box Model
Width and Height of an Element
CSS Forms
Styling Input Fields
The example above applies to all <input> elements. If you only want to style a specific
input type, you can use attribute selectors:
• input[type=text] - will only select text fields
• input[type=password] - will only select password fields
• input[type=number] - will only select number fields
• etc..
<input> element with padding, margin and border properties
Output:
Output:
CSS Image Gallery
The following image gallery is created with CSS:
<html>
<head>
<style>
[Link] {
margin: 5px;
border: 1px solid #ccc;
float: left;
width: 180px;
}
[Link]:hover {
border: 1px solid #777;
}
[Link] img {
width: 100%;
height: auto;
}
[Link] {
padding: 15px;
text-align: center;
}
</style>
</head>
<body>
<div class="gallery">
<a target="_blank" href="img_5terre.jpg">
<img src="img_5terre.jpg" alt="Cinque Terre" width="600" height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="gallery">
<a target="_blank" href="img_forest.jpg">
<img src="img_forest.jpg" alt="Forest" width="600" height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="gallery">
<a target="_blank" href="img_lights.jpg">
<img src="img_lights.jpg" alt="Northern Lights" width="600" height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="gallery">
<a target="_blank" href="img_mountains.jpg">
<img src="img_mountains.jpg" alt="Mountains" width="600" height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>
</body>
</html>
CSS Website Layout
A website is often divided into headers, menus, content and a footer:
Header
A header is usually located at the top of the website (or right below a top navigation
menu). It often contains a logo or the website name:
Navigation Bar
A navigation bar contains a list of links to help visitors navigating through your website.
Content
The layout in this section, often depends on the target users. The most common layout is
one (or combining them) of the following:
• 1-column (often used for mobile browsers)
• 2-column (often used for tablets and laptops)
• 3-column layout (only used for desktops)
Footer
The footer is placed at the bottom of your page. It often contains information like
copyright and contact info.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>CSS Website Layout</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
}
/* Style the header */
.header {
background-color: #f1f1f1;
padding: 20px;
text-align: center;
}
/* Style the top navigation bar */
.topnav {
overflow: hidden;
background-color: #333;
}
/* Style the topnav links */
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
/* Change color on hover */
.topnav a:hover {
background-color: #ddd;
color: black;
}
/* Create three equal columns that floats next to each other */
.column {
float: left;
width: 30%;
padding: 15px;
}
/* Clear floats after the columns */
.row::after {
content: "";
display: table;
clear: both;
}
/* Responsive layout - makes the three columns stack on top of each other instead of next
to each other */
@media screen and (max-width:600px) {
.column {
width: 100%;
}
}
/* Style the footer */
.footer {
background-color: #a9a6a6;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<div class="header">
<h1>Header</h1>
</div>
<div class="topnav">
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
</div>
<div class="row">
<div class="column">
<h2>Column</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet
pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna
tristique. Quisque vehicula, risus eget aliquam placerat, purus leo tincidunt eros, eget
luctus quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.</p>
</div>
<div class="column">
<h2>Column</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet
pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna
tristique. Quisque vehicula, risus eget aliquam placerat, purus leo tincidunt eros, eget
luctus quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.</p>
</div>
<div class="column">
<h2>Column</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet
pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna
tristique. Quisque vehicula, risus eget aliquam placerat, purus leo tincidunt eros, eget
luctus quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.</p>
</div>
</div>
<div class="footer">
<p>Footer</p>
</div>
</body>
</html>