Getting Started with CSS
In this tutorial you’ll learn how easy it is to add style and formatting information to the web pages using CSS. But, before we begin, make sure that you have some working knowledge of HTML.
Introduction
CSS stands for Cascading Style Sheets. It is a language that describes the style of an HTML document. In simple words, it tells the browser how to display the text and other content that you write in HTML. An example of CSS code is shown below:
body { background-color: lightblue; } h1 { color: white; text-align: center; } p { font-family: verdana; font-size: 20px; }
The style above defines how the paragraph tag <p>
should look, which font it needs to have and what size it should be. Similarly, it goes for the other tags like <h1>
or body tag. These definitions are normally saved in external .css files. With an external stylesheet file, you can change the look of an entire website by changing just one file!
Including CSS in HTML Documents
CSS can either be attached as a separate document or embedded in the HTML document itself. There are three methods of including CSS in an HTML document:
- Inline styles — Using the style attribute in the HTML start tag.
- Embedded styles — Using the <style> element in the head section of a document.
- External style sheets — Using the <link> element, pointing to an external CSS file.
Inline Styles
Inline styles are used to apply the unique style rules to an element by putting the CSS rules directly into the start tag. It can be attached to an element using the style
attribute.
<h1 style="color:red; font-size:30px;">This is a heading</h1> <p style="color:green; font-size:22px;">This is a paragraph.</p> <div style="color:blue; font-size:14px;">This is some text content.</div>
Using the inline styles are generally considered as a bad practice. As style rules are embedded directly inside the HTML tag, it causes the presentation to become mixed with the content of the document; which makes the code hard to maintain and negates the purpose of using CSS.
Embedded Style Sheets
Embedded or internal style sheets only affect the document they are embedded in. They are defined in the </head> section of an HTML document using the <style>
element. You can define any number of <style>
elements in an HTML document but they must appear between the <head> and </head> tags. Let’s take a look at an example:
<!DOCTYPE html> <html lang="en"> <head> <title>My HTML Document</title> <style> body { background-color: YellowGreen; } p { color: #fff; } </style> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph of text.</p> </body> </html>
External Style Sheets
An external style sheet is ideal when the style is applied to many pages of the website. It holds all the style rules in a separate document that you can link from any HTML file on your site. External style sheets are the most flexible because with an external style sheet, you can change the look of an entire website by changing just one file.
You can attach external style sheets in two ways — linking and importing.
Linking External Style Sheets
Before linking, we need to create a style sheet first. Let’s open your favorite code editor and create a new file. Now type the following CSS code inside this file and save it as “style.css“.
body { background: lightyellow; font: 18px Arial, sans-serif; } h1 { color: orange; }
An external style sheet can be linked to an HTML document using the <link>
tag. The <link>
tag goes inside the <head>
section, as you can see in the following example:
<!DOCTYPE html> <html lang="en"> <head> <title>My HTML Document</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph of text.</p> </body> </html>
Importing External Style Sheets
The @import rule is another way of loading an external style sheet. The @import statement instructs the browser to load an external style sheet and use its styles.
You can use it in two ways. The simplest is within the header of your document. Note that, other CSS rules may still be included in the <style>
element. Here’s an example:
<style> @import url("css/style.css"); p { color: blue; font-size: 16px; } </style>
CSS Syntax
A CSS rule-set consists of a selector and a declaration block:
- The selector points to the HTML element/tag 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.
- A CSS declaration always ends with a semicolon, and declaration blocks are surrounded by curly braces.
In this example below <p> tag will be center-aligned, with a green text color:
p { color: green; text-align: center; }
CSS Comments
Comments are usually added with the purpose of making the source code easier to understand. It may help other developer (or you in the future when you edit the source code) to understand what you were trying to do with the CSS. Comments are significant to programmers but ignored by browsers.
A CSS comment begins with /*
, and ends with */
, as shown in the example below:
/* This is a CSS comment */ h1 { color: blue; text-align: center; } /* This is a multi-line CSS comment that spans across more than one line */ p { font-size: 18px; text-transform: uppercase; }
CSS property names and many values are not case-sensitive. Whereas, CSS selectors are usually case-sensitive, for instance, the class selector
.maincontent
is not the same as.mainContent
.
CSS Selectors
CSS selectors are used to “find” (or select) HTML elements based on their element name, id, class, attribute, and more. There are many kinds of selectors available in CSS such as:
- Element Selector
- ID Selector
- Class Selector
- Grouping Selectors
Element Selector
The element selector selects elements based on the element name. For example, the <p> elements in below example has been styled to be center-aligned, with a green text color:
p { text-align: center; color: green; }
ID Selector
The id selector uses the id attribute of an HTML element to select a specific element. The element should be unique within a page. To select an element with a specific id, write a hash (#) character, followed by the id of the element. For example, to apply style to paragraph with id = “para”:
<p id="para">Test Example</p>
The following style rules be applied:
#para { text-align: center; color: red; }
Class Selector
The class selector uses the class attribute of an HTML element to select a specific class element. The element have no conditions to be unique. To select an element with a specific class, write a hash (.) character, followed by the class name of the elements. For example, to apply style to paragraph with class = “para”:
<p class="para">Test Example</p>
The following style rules be applied:
.para { text-align: center; color: red; }
The rule will get applied to all the elements that has the class “para”.
Grouping Selector
Often several selectors in a style sheet share the same style rules declarations. You can group them into a comma-separated list to minimize the code in your style sheet. It also prevents you from repeating the same style rules over and over again. Let’s take a look:
h1, h2, h3 { font-weight: normal; }
CSS Units
CSS has several different units for expressing a length. Many CSS properties take “length” values, such as width, margin, padding, font-size, etc. Length is a number followed by a length unit, such as 10px, 2em, etc.
The units in which length is measured can be either absolute such as pixels, points and so on, or relative such as percentages (%
) and em
units (Specifying CSS units is obligatory for non-zero values, because there is no default unit).
Relative Length Units
Relative length units specify a length relative to another length property. Relative units are:
Unit | Description |
---|---|
em | the current font-size |
ex | the x-height of the current font |
The em
and ex
units depend on the font size that’s applied to the element.
Absolute Length Units
Absolute length units are fixed in relation to each other. They are highly dependent on the output medium, so are mainly useful when the output environment is known. The absolute units consist of the physical units (in
, cm
, mm
, pt
, pc
) and the px
unit.
Unit | Description |
---|---|
in |
inches – 1in is equal to 2.54cm. |
cm |
centimeters. |
mm |
millimeters. |
pt |
points – In CSS, one point is defined as 1/72 inch (0.353mm). |
pc |
picas – 1pc is equal to 12pt. |
px |
pixel units – 1px is equal to 0.75pt. |
Note: Absolute physical units such as in
, cm
, mm
, etc. should be used for print media and similar high-resolution devices. Whereas, for on-screen display such as desktop and lower-resolution devices, it is recommended to use the pixel or em units.
h1 { margin: 0.5in; } /* inches */ h2 { line-height: 3cm; } /* centimeters */ h3 { word-spacing: 4mm; } /* millimeters */ h4 { font-size: 12pt; } /* points */ h5 { font-size: 1pc; } /* picas */ h6 { font-size: 12px; } /* picas */
CSS Colors
The color
property defines the text color (foreground color in general) of an element.
For instance, the color
property specified in the body
selector defines the default text color for the whole page. Let’s try out the following example to see how it works:
body { color: #ff5722; }
Colors in CSS most often specified in the following formats:
- a color keyword – like “red”, “green”, “blue”, “transparent”, etc.
- a HEX value – like “#ff0000”, “#00ff00”, etc.
- an RGB value – like “rgb(255, 0, 0)”
/* Color Keywords */ h1 { color: red; } p { color: purple; } /* HEX Color Values */ h1 { color: #ffa500; } p { color: #00ff00; } /* RGB Color Values */ h1 { color: rgb(255, 165, 0); } p { color: rgb(0, 255, 0); }
CSS Spacing
There are 2 important concepts when it comes to CSS spacing i.e Margin and Padding. You can use CSS code to reduce or increase the spacing of elements by using the padding and margin CSS commands.
CSS Margin Properties
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).
Example: Set different margin for all four sides of a <div> element:
div { margin-top: 100px; margin-bottom: 100px; margin-right: 150px; margin-left: 80px; }
Note: If you wish to apply same margin across all the sides then simply using margin shorthand property rather direction (top,bottom,left,right).
div { margin: 100px; }
CSS Padding Properties
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).
Example: Set different padding for all four sides of a <div> element:
div { padding-top: 50px; padding-right: 30px; padding-bottom: 50px; padding-left: 80px; }
Note: If you wish to apply same padding across all the sides then simply using padding rather direction (top,bottom,left,right).
Example: Set same margin for all four sides of a <div> element:
div { margin: 100px; }
CSS Dimensions
CSS has several dimension properties, such as width
, height
, max-width
, min-width
, max-height
, and min-height
that allows you to control the width and height of an element. The following sections describe how to use these properties to create a better web page layout.
Setting the Width and Height
The width
and height
property defines the width and height of the content area of an element.
This width and height does not include paddings, borders, or margins. See the CSS box model to know how the effective width and height of an element’s box is calculated.
Let’s try out the following example and see how it actually works
div { width: 300px; height: 200px; }
The above style rules assigns a fixed width of 300 pixels and height of 200px to the <div>
element.
The width
and height
properties can take the following values:
- length – specifies a width in px, em, rem, pt, cm, etc.
- % – specifies a width in percentage (%) of the width of the containing element.
- auto – the browser calculates a suitable width for the element.
- initial – Sets the width and height to its default value, which is
auto
. - inherit – specifies that the width should be inherited from the parent element.
Note: You can not specify negative values to the width and height properties.
Setting Maximum Width and Height
You can use the max-width
and max-height
property to specify the maximum width and height of the content area. This maximum width and height does not include paddings, borders, or margins.
An element cannot be wider than the max-width
value, even if the width
property value is set to something larger. For instance, if the width
is set to 300px and the max-width
is set to 200px, the actual width of the element will be 200px. Let’s check out an example:
div { width: 300px; max-width: 200px; }
Likewise, an element that has max-height
applied will never be taller than the value specified, even if the height
property is set to something larger. For example, if the height
is set to 200px and the max-height
set to 100px, the actual height of the element will be 100px.
div { height: 200px; max-height: 100px; }
Setting Minimum Width and Height
You can use the min-width
and min-height
property specify the minimum width and height of the content area. This minimum width and height does not include paddings, borders, or margins.
An element cannot be narrower than the min-width
value, even if the width
property value is set to something lesser. For example, if the width
is set to 300px and the min-width
is set to 400px, the actual width of the element will be 400px. Let’s see how it actually works:
div { width: 200px; min-width: 300px; }
Similarly, an element to which min-height
is applied will never be smaller than the value specified, even if the height
property is set to something lesser. For example, if the height
is set to 200px, and the min-height
is set to 300px, the actual height of the element will be 300px.
div { height: 100px; min-height: 200px; }
CSS Font
CSS provide several properties for styling the font of the text, including changing their face, controlling their size and boldness, managing variant, and so on.
The font properties are: font-family
, font-style
, font-weight
, font-size
, and font-variant
.
Let’s have a look at each of these font properties one by one.
Font Family
The font-family
property is used to specify the font to be used to render the text.
This property can hold several comma-separated font names as a fallback system, so that if the first font is not available on the user’s system, browser tries to use the second one, and so on.
Hence, list the font that you want first, then any fonts that might fill in for the first if it is not available. You should end the list with a generic font family which are five — serif
, sans-serif
, monospace
, cursive
and fantasy
. A typical font family declaration might look like this:
body { font-family: Arial, Helvetica, sans-serif; }
If the name of a font family contains more than one word, it must be placed inside quotation marks, like
"Times New Roman"
,"Courier New"
,"Segoe UI"
, etc.
Font Style
The font-style
property is used to set the font face style for the text content of an element. The font style can be normal
, italic
or oblique
. The default value is normal
.
Let’s try out the following example to understand how it basically works:
p.normal { font-style: normal; } p.italic { font-style: italic; } p.oblique { font-style: oblique; }
Font Size
The font-size
property is used to set the size of font for the text content of an element.
There are several ways to specify the font size values e.g. with keywords, percentage, pixels, ems, etc.
Let’s try out the following example to understand how it basically works:
h1 { font-size: 24px; } p { font-size: 14px; }
Font Weight
The font-weight
property specifies the weight or boldness of the font.
This property can take one of the following values: normal
, bold
, bolder
, lighter
, 100
, 200
, 300
, 400
, 500
, 600
, 700
, 800
, 900
and inherit
.
- The numeric values
100
–900
specify the font weights, where each number represents a weight greater than its predecessor.400
is same asnormal
&700
is same asbold
. - The
bolder
andlighter
values are relative to the inherited font weight, while the other values such asnormal
andbold
are absolute font weights.
Let’s try out an example to understand how this property basically works:
p { font-weight: bold; }
Font Variant
The font-variant
property allows the text to be displayed in a special small-caps variation.
Small-caps or small capital letters are slightly different to normal capital letters, in which lowercase letters appear as smaller versions of the corresponding uppercase letters.
Try out the following example to understand how this property actually works:
p { font-variant: small-caps; }
Note: The value normal
removes small caps from the text which is already formatted that way.
CSS Decoration
CSS provides several decoration properties that allows you to define various text styles such as color, alignment, spacing, decoration, transformation, etc. very easily and effectively.
The commonly used text properties are: text-align
, text-decoration
, text-transform
, text-indent
, line-height
, letter-spacing
, word-spacing
, and more. These properties give you precise control over the visual appearance of the characters, words, spaces, and so on.
Let’s see how to set these text properties for an element in more detail.
Text Color
The color of the text is defined by the CSS color
property.
The style rule in the following example will define the default text color for the page
body { color: #434343; }
Text Alignment
The text-align
property is used to set the horizontal alignment of the text. It can be aligned in four ways: to the left, right, centre or justified (straight left and right margins).
Let’s take a look at an example to understand how this property basically works.
h1 { text-align: center; } p { text-align: justify; }
Text Decoration
The text-decoration
property is used to set or remove decorations from text.
This property typically accepts one of the following values: underline
, overline
, line-through
, and none
. You should avoid underline text that is not a link, as it might confuse the visitor.
Let’s try out the following example to understand how it basically works:
h1 { text-decoration: overline; } h2 { text-decoration: line-through; } h3 { text-decoration: underline; }
Removing the Default Underline from Links
The text-decoration
property is extensively used to remove the default underline from the HTML hyperlinks. You can further provide some other visual cues to make it stand out from the normal text, for example, using dotted border instead of solid underline.
Let’s take a look at the following example to understand how it basically works:
a { text-decoration: none; border-bottom: 1px dotted; }
Text Transformation
The text-transform
property is used to set the cases for a text.
Text are often written in mixed case. However, in certain situations you may want to display your text in entirely different case. Using this property you can change an element’s text content into uppercase or lowercase letters, or capitalize the first letter of each word without modifying the original text.
Let’s try out the following example to understand how it basically works:
h1 { text-transform: uppercase; } h2 { text-transform: capitalize; } h3 { text-transform: lowercase; }
Text Indentation
The text-indent
property is used to set the indentation of the first line of text within a block of text. It is typically done by inserting the empty space before the first line of text.
The size of the indentation can be specified using percentage (%), length values in pixels, ems, etc.
The following style rule will indent the first line of the paragraphs by 100 pixels.
p { text-indent: 100px; }
Letter Spacing
The letter-spacing
property is used to set extra spacing between the characters of text.
This property can take a length value in pixels, ems, etc. It may also accept negative values. When setting letter spacing, a length value indicates spacing in addition to the default inter-character space.
Let’s check out the following example to understand how it really works:
h1 { letter-spacing: -3px; } p { letter-spacing: 10px; }
Word Spacing
The word-spacing
property is used to specify additional spacing between the words.
This property can accept a length value in pixels, ems, etc. Negative values are also allowed.
Let’s try out the following example to understand how this property works:
p.normal { word-spacing: 20px; } p.justified { word-spacing: 20px; text-align: justify; } p.preformatted { word-spacing: 20px; white-space: pre; }
Line Height
The line-height
property is used to set the height of the text line.
It is also called leading and commonly used to set the distance between lines of text.
The value of this property can be a number, a percentage (%), or a length in pixels, ems, etc.
p { line-height: 1.2; }
CSS Positioning
Positioning elements appropriately on the web pages is a necessity for a good layout design. There are several methods in CSS that you can use for positioning elements. The following section will describe you these positioning methods one by one.
Static Positioning
A static positioned element is always positioned according to the normal flow of the page. HTML elements are positioned static by default. Static positioned elements are not affected by the top
, bottom
, left
, right
, and z-index
properties.
.box {
position: static;
padding: 20px;
background: #7dc765;
}
Relative Positioning
A relative positioned element is positioned relative to its normal position.
In the relative positioning scheme the element’s box position is calculated according to the normal flow. Then the box is shifted from this normal position according to the properties — top
or bottom
and/or left
or right
.
.box { position: relative; left: 100px; }
Absolute Positioning
An absolutely positioned element is positioned relative to the first parent element that has a position other than static. If no such element is found, it will be positioned on a page relative to the ‘top-left’ corner of the browser window. The box’s offsets further can be specified using one or more of the properties top
, right
, bottom
, and left
.
Absolutely positioned elements are taken out of the normal flow entirely and thus take up no space when placing sibling elements. However, it can overlap other elements depending on the z-index
property value. Also, an absolutely positioned element can have margins, and they do not collapse with any other margins.
.box { position: absolute; top: 200px; left: 100px; }
Fixed Positioning
Fixed positioning is a subcategory of absolute positioning.
The only difference is, a fixed positioned element is fixed with respect to the browser’s viewport and does not move when scrolled.
.box { position: fixed; top: 200px; left: 100px; }
Want More?
Here are few additional resources for you to learn and practice: