Next to HTML, CSS is the most important standard in web design. If you want to write con­tem­po­rary web pages by hand, you won’t be able to do it without using CSS. It’s also easier to handle graphic HTML editors, homepage kits, or content man­age­ment systems if you have basic CSS knowledge. Our CSS tutorial sub­scribes to the motto of “CSS coding made easy”, and in­tro­duces you to the basics of the stylesheet language in the form of a crash course.

Sep­a­ra­tion of content and pre­sen­ta­tion

In com­bi­na­tion with HTML, CSS offers a sep­a­ra­tion between content and pre­sen­ta­tion. The Hypertext Markup Language (HTML) is used to sup­ple­ment text documents with in­for­ma­tion that’s then used for the semantic struc­tur­ing of the text elements. The markup language creates the basis for every website: the HTML code. This describes the elements from which a document is composed (e.g.: <body>, <header>, <footer>,) and how the in­for­ma­tion should be in­ter­pret­ed (e.g.: Headline <h1>, text paragraph <p>, line break <br>, link <a>, photo <img>, video <video>). This is enough for web browsers to be able to display HTML documents as web pages. But from today’s point of view, the result isn’t very appealing. A decisive step is missing: in­di­vid­ual for­mat­ting.

Orig­i­nal­ly, HTML also offered rudi­men­ta­ry design in­struc­tions. But with HTML5, these are con­sid­ered outdated and shouldn’t be used anymore. Instead, the stylesheet language CSS (Cascading Style Sheets) is used to sep­a­rate­ly manage pre­sen­ta­tion re­quire­ments. But what exactly is CSS?

What is CSS?

Like HTML, CSS is also notated in text form. This can take place directly in the HTML document (inline for each document or just once in the HTML header). Generally, though, web designers bind separate CSS documents together to format web pages. The result is a clear source code with elim­i­nat­ed redundant design in­struc­tions by referring to separate stylesheets. The fewer rep­e­ti­tions, the leaner the source code. This is reflected online in shorter download times and a faster site loading time. CSS also fa­cil­i­tates the main­te­nance of a website. If adap­ta­tions to the design are necessary, these are made in the central CSS files, so it’s not necessary to look through each in­di­vid­ual HTML document and adapt them sep­a­rate­ly. As a living standard, CSS is con­tin­u­al­ly developed by the World Wide Web Con­sor­tium (W3C) and is currently available in its third version as CSS3. While the versions CSS1 and CSS2 have long been in­te­grat­ed in all current browsers, the newly in­tro­duced prop­er­ties of the third version are not yet uni­ver­sal­ly supported. A support overview for the popular browser models Microsoft Internet Explorer, Mozilla Firefox, Google Chrome, Apple Safari, and Opera is offered by w3schools.com.

Basic structure: The CSS syntax

The central purpose of CSS is to define the design of a website. For this reason, the un­der­ly­ing HTML elements are assigned certain values using the stylesheet language. The basic structure of a design in­struc­tion looks as follows:

Selector { Declaration }

Selector deals with the rep­re­sen­ta­tion of the HTML elements being defined by the design in­struc­tion. The de­c­la­ra­tion subsists of a property-value com­bi­na­tion, which is then listed in the braces. Every de­c­la­ra­tion ends with a semicolon:

HTML element { Property: Value;}

In this format, for example, you can assign a font color to a headline:

h2 { color: red; }

The selector h2 rep­re­sents the second headline class. The de­c­la­ra­tion contains the property color and the value red. On a website with such a design in­struc­tion, all text passages marked with <h2> in the source code would be displayed as red. Al­ter­na­tive­ly, detailed color settings can be defined using hexa­dec­i­mal color codes (see the chapter on CSS color).

h2 { color: #ff0000; }

Web designers have the option to assign a single property to a selector, or to define extensive rule sets that contain detailed design in­struc­tions. For the sake of clarity, a spelling has been es­tab­lished in which all prop­er­ties of a rule set are listed together:

Selector {
    Property1: Value;
    Property2: Value;
    Property3: Value;
}

For example, such a property bundle could look as follows:

h2 { 
    color: #ff0000; 
    font-family: Helvetica, sans-serif; 
    font-size: 19px; 
    font-weight: bold;
    text-align: center; 
}

The property-value com­bi­na­tions in the braces define the font color, font family, font size, font style, and alignment of the text. A detailed de­scrip­tion of the CSS prop­er­ties will follow in this tutorial.

A rule set may also specify several selectors. In this case, they’re separated by commas before the de­c­la­ra­tion:

Selector1, Selector 2 { Declaration }

CSS Selectors

CSS supports various selectors that enable user-defined, custom design in­struc­tions. But for getting started, it’s suf­fi­cient to fa­mil­iar­ize yourself with type, class, ID, and universal selectors.

Type of selector CSS notation De­scrip­tion
Type selector HTML element (e.g. h2) A type selector cor­re­sponds to the name of the element to which it refers. For­mat­ting is applied to all HTML elements of the same type.
Class selector .example A class selectors refers to all elements of a certain class. Class selectors are formed with a period (.) and a chosen class name: .example. Classes are assigned to HTML elements using the class attribute (class=“example”).
ID #example An ID selector is an element with a unique ID. These are in­te­grat­ed in the HTML source code with the id attribute (id=“example”).
Universal selector * The universal selector asterisk (*) refers to all HTML elements in a document.

The use of various CSS selectors can be il­lus­trat­ed with simple examples. The following line of code shows the type selector h2 with de­c­la­ra­tion:

h2 { 
    color: #305796; 
    font-family: Helvetica, sans-serif; 
}

The for­mat­ting applies to all HTML elements with the type h2 (second headline class).

Al­ter­na­tive­ly, the CSS for­mat­ting can be performed using a class selector. This allows web designers to provide the same design in­struc­tions re­gard­less of type.

.content { 
    color: #ff0000; 
    font-family: Helvetica, sans-serif; 
}

This for­mat­ting applies to all HTML elements to which the class .content have been assigned. The as­sign­ment is formatted as follows:

<p class="special-text">Beispieltext</p>
Tip

In HTML the class name is notated without a period (.).

If a design in­struc­tion refers only to a single element in the HTML source code, an ID selector can be used. The following example shows the for­mat­ting of a nav­i­ga­tion area:

#navigation {
    font-family: Helvetica, sans-serif; 
    background-color: #8ad8d4;
    border: 2px solid #448278;
}

The as­sign­ment of the for­mat­ting is put in the HTML source code without a hashtag (#):

<div id="navigation">
    <ul>
        <li><a href="index.htm">Homepage</a></li>
        <li><a href="legal.htm">Legal</a></li>
    </ul>
</div>

The benefit of using an ID selector is that you can see, at a glance, which sections in the source text are unique. ID selectors also take priority when assigning styles. If a par­tic­u­lar element finds that class and ID for­mat­ting are con­tra­dict­ing one another, the latter will be used. Classes, in turn, take higher priority than type selectors.

Classes, as well as IDs, are free to be named whatever you want. But keep in mind that CSS selectors are case sensitive: Upper and lower case dif­fer­ences are in­ter­pret­ed as separate classes (e.g. nav­i­ga­tion vs. Nav­i­ga­tion). Empty and special char­ac­ters aren’t allowed, and umlauts are unusual.

If a design in­struc­tion refers to all elements of an HTML document, then the asterisk (*) is used:

*  { 
    font-family: Helvetica, sans-serif; 
}

In this example, all text elements of the website will now be shown in Helvetica font in the browser.

In­te­grat­ing CSS in HTML

For a browser to consider CSS for­mat­ting in the context of the website layout, the design in­struc­tions need to be linked with the HTML source code. Users have three options:

  • Direct in­te­gra­tion of the CSS de­c­la­ra­tion into HTML tags
  • CSS markup in the HTML header
  • Reference to a separate stylesheet

The last solution is generally con­sid­ered to be the best: In practice, stylesheets are usually created as external text files and then in­te­grat­ed.

CSS de­c­la­ra­tion in HTML tags

If a CSS de­c­la­ra­tion is formatted to a single place in the source text, then the style attribute can be used to specify it directly in the in­tro­duc­to­ry tag of the HTML element to which the design statement is referring. In this case, it’s called “inline style”.

<h2 style=“color: red;”>subheading</h2>

This is ad­van­ta­geous because you don’t need to create your own stylesheet, the selector is left out and the as­sign­ment has a high priority. When an entire rule set is used, though, this form of for­mat­ting can become confusing and redundant.

<h2 style="color: #ff0000; font-family: 'Helvetica New', sans-serif; font-size: 19px; font-weight: bold; text-align: center;">subheading</h2>

This in­te­gra­tion of design in­struc­tions is rec­om­mend­ed only (if at all) for small websites with minimal for­mat­ting.

CSS markup in the HTML header

If the same design in­struc­tion is to be used several times for the same element within an HTML document (e.g. for all h2 on the webpage), then putting a CSS de­c­la­ra­tion in the HTML tag isn’t enough. Instead, it’s rec­om­mend­ed to define the cor­re­spond­ing design in­struc­tions just one time using the style element of the HTML header of the document.

<!DOCTYPE html>
    <html lang="en">
        <head>
            <style>
                h2 {
                    color: #ff0000; 
                    font-family: 'Helvetica New', sans-serif; 
                    font-size: 19px; 
                    font-weight: bold;
                    text-align: center; 
                }
            </style>
        </head>
        <body>
            <h2>Subheading1</h2>
            […]
            <h2>Subheading2</h2>
            […]
        </body>
</html>

The rule set within the style element is au­to­mat­i­cal­ly applied to all following h2 elements. But what if the h2 element is also being used on other pages within the same online project, and should also employ the same design in­struc­tions? In this case, website operators would have to integrate the code block with the in­struc­tion into each HTML site and adapt each in­di­vid­u­al­ly to any new changes. But with a central CSS file, this problem is given an elegant solution.

Reference to a separate stylesheet

If design in­struc­tions are defined in a separate stylesheet, then these must be in­te­grat­ed into the un­der­ly­ing HTML document. This is done using the HTML element <link>, which, like the style element, is a child element of the head element.

<link rel=“stylesheet” href=“example.css”>

The link element contains the oblig­a­tory at­trib­ut­es rel and href and can be op­tion­al­ly sup­ple­ment­ed with the at­trib­ut­es type and media.

link element at­trib­ut­es De­scrip­tion
rel The rel attribute defines the type re­la­tion­ship type of the element. The value stylesheet indicates that a stylesheet should be in­te­grat­ed.
href The href attribute ref­er­ences the file that should be in­te­grat­ed as a stylesheet.
type The optional attribute type describes the type of media of the in­te­grat­ed file – in the case of CSS, “text/css”.
media With the media attribute website operators can choose whether the ref­er­enced stylesheet should only be used with a certain output medium. This allows different stylesheets to be made available for various end devices. Possible values are, for example, screen or print.

CSS color spec­i­fi­ca­tions

As mentioned in the in­tro­duc­to­ry chapter, color as­sign­ments via CSS can be defined using the English color words (e.g. red, blue, green). In practice, though, you don’t find design in­struc­tions like this very often. More commonly the RGB model is used. This offers sig­nif­i­cant­ly more shades, and allows website operators to define detailed color settings. The cor­re­spond­ing codes can be de­ter­mined using a color selector. Google offers this, for example, in the form of Quick Answer.

The RGB model

In the RGB model, every color can be precisely specified by its pro­por­tions of the basic colors red (R), green (G), and blue (B).

Color pro­por­tions in the RGB model are defined using decimal values between 0 and 255. While a value of 0 means that a color has no per­cent­age of that par­tic­u­lar base color, a value of 255 means a maximum pro­por­tion.

The notation of RGB color values cor­re­sponds to the following scheme (the spaces aren’t necessary):

rgb(Red value, green value, blue value)

In this way, the RGB model enables you to define around 16.7 million different colors for the design of your website. The following table shows the RGB values for the standard colors black, white, red, blue, green, yellow, magenta, cyan, violet, and orange:

Since CSS3, RGB values can be expanded by a fourth value: the so-called alpha channel (a). This specifies the opacity of the color and is given in values from 0 to 1 (e.g. 0.8).

rgba(red value, green value, blue value, opacity)

For example, the following RGBA values give the basic color blue, as il­lus­trat­ed above, with a trans­paren­cy of 50 percent.

rgba(0, 0, 255, 0.5)

The following graphic shows a trans­par­ent blue color field laid over a red color field.

Al­ter­na­tive­ly, the spec­i­fi­ca­tion of colors in hex values instead of decimal notation has been es­tab­lished for use online.

Hex­idec­i­mal color codes

Hex­idec­i­mal color codes define color values by means of a score system with the base 16. Unlike the decimal system, not 10 but 16 digits are used in the following order: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f.

The basic structure of a hexa­dec­i­mal color code is a hashtag (#) followed by six hexa­dec­i­mal digits, which are rep­re­sent­ed in blocks of two for each color in the RGB model (red, green, blue):

#RRGGBB

The sat­u­ra­tion of each color is indicated by the hexa­dec­i­mal number value. 00 means a complete absence of that color, and FF (decimal: 255) means maximum color sat­u­ra­tion. The re­spec­tive color is based on an additive mixture of the basic colors. For example, the following hex values are for the same color samples already shown in the RGB code example:

In addition to RGB, CSS also supports the HSL color model. In the future, web designers will also be able to define color settings via CMYK.

The most important CSS prop­er­ties

With CSS, you can choose from around 420 prop­er­ties with which to define your design in­struc­tions for HTML elements. Each property accepts a specified set of values. For the sake of clarity, CSS prop­er­ties are divided by ap­pli­ca­tion area. The font, color ad­just­ments, text for­mat­ting, and layout using the CSS box model, and the po­si­tion­ing of CSS boxes, are of central im­por­tance. Our crash course in CSS for beginners con­cen­trates on the most important prop­er­ties for an in­tro­duc­tion to Cascading Style Sheets, and demon­strates the creation of CSS rule sets by means of practical code examples. A complete list of all CSS prop­er­ties can be found on the W3C website.

Font

Fonts are a central feature of a website. CSS offers you diverse pos­si­bil­i­ties for for­mat­ting the writing elements of an HTML site. The most important prop­er­ties in text for­mat­ting are:

  • font-family
  • font-style
  • font-variant
  • font-size
  • line-height
  • font-weight

font-family

Should a par­tic­u­lar font be defined for the text elements of a website, then the CSS property font-family is used. This allows you to create a font stack. This is a pri­or­i­tized list of suitable fonts. Font stacks are built in such a way that the desired font is named first, followed by a list of matching display al­ter­na­tives.

.content {
    font-family: Georgia, Garamond, serif;
}

The example shows a design in­struc­tion for the .content class in the CSS file. This is referred to in the HTML document through the class attribute and class name content:

<p class=“content”>Example text</p>

Georgia is defined as a pri­or­i­tized font, with Garamond as the al­ter­na­tive font. This way, a web browser is in­struct­ed to display the text section in Garamond if Georgia isn’t installed on the system.

But what if no named al­ter­na­tive is available? In such a case, it is rec­om­mend­ed to define a generic font as a fallback mechanism. Georgia as well as Garamond belong to the serif font family. If these are included in the de­c­la­ra­tion as the last al­ter­na­tives, then the web browser displays the paragraph in a font of the generic family available to it – for example, in the wide­spread Times New Roman font. This ensures that an effect intended by the stylesheet author is at least retained in its basic features.

Other generic families are sans-serif (e.g. Arial, Trebuchet, or Verdana) and monospace (e.g. Courier, Courier New, or Andale Mono). Fonts whose names consist of several words are placed in single or double quotes in the CSS de­c­la­ra­tion:

.content {
    font-family: 'Trebuchet MS', 'Liberation Sans', sans-serif;
}
Tip

Generic families are keywords that cannot be quoted in quotation marks.

font-style

The CSS property font-style refers to the font style of a paragraph, and allows you to define design in­struc­tions for the in­cli­na­tion of excellent char­ac­ters.

Value for text in­cli­na­tion De­scrip­tion
normal Normal font style (standard settings)
italic Cursive font
oblique Slanted font

The following example shows a design in­struc­tion for the cursive font style:

.special-content {
    font-family: Arial;
    font-style: italic;
}
<p class=“special-content”>Example text</p>

The values italic and oblique are generally displayed iden­ti­cal­ly in web browsers, but the value oblique is used less often. The dif­fer­ence between it and the italic value is that oblique will slant a normal font, even if it doesn’t provide an ital­i­cized variant.

font-variant

The CSS property font-variant is used to define font vari­a­tions.

Value for font variants De­scrip­tion
normal Normal font variant (standard settings)
small-caps Small capitals replace lowercase letters
all-small-caps Small capitals replace both uppercase and lowercase letters

The following examples show the font variants small-caps and all-small-caps:

.content {
            font-family: Arial;
            font-variant: small-caps;
    }
    <p class=“content”>Example text</p>

The value small-caps instructs the web browser to display all lowercase letters as small capitals (uppercase letters the size of the smaller case).

.content {
            font-family: Arial;
            font-variant: all-small-caps;
    }
    <p class=“content;”>Example text</p>

The value all-small-caps instructs the web browser to display all letters as small capitals.

font-size

With the CSS property font-size, the display size of the text elements is defined. This can be done in absolute values or in relation to sur­round­ing elements. The font size, or height of the char­ac­ters, is given here. Web designers have various spellings and units of mea­sure­ments available.

Absolute mea­sure­ments are oriented in physical length. But on the screen, browsers calculate all units in pixels using a res­o­lu­tion of 96 dpi. On a modern laptop or smart­phone, for example, 1 cm will be sig­nif­i­cant­ly smaller than would be expected. Other than px, absolute units of mea­sure­ment hardly play a role in web design. The only way to make sense of them is to print out where the browser it targeting real sizes.

Absolute mea­sure­ments:

Unit CSS notation De­scrip­tion
Pixel px The mea­sure­ment px was developed specially for CSS and rep­re­sents the size of an element in pixels. Pixels are displayed in relation to point density (i.e. dots per inch, dpi). It is still a definite unit, though. 1 px today doesn’t nec­es­sar­i­ly cor­re­spond to a display pixel. To prevent text elements from being displayed too small, browsers work on high-res­o­lu­tion displays with a scale of the px measure unit. A CSS pixel is rep­re­sent­ed by several display pixels, depending on the screen res­o­lu­tions. The following applies as a guideline for scaling: 1 CSS pixel is 1/96 of an inch. Users can change the as­sign­ment of px unit to device pixel by zooming in on the browser.
Cen­time­ters cm Size in cen­time­ters
Mil­lime­ters mm Size in mil­lime­ters
Inches in Size in inches (1 in = 2.54 cm)
Points pt Size in points (1 point rep­re­sents 1/72 of an inch)
Pica pc Size in pica (1 pica rep­re­sents 12 points)

With relative units of measure, the font size is a function of a pre-de­ter­mined variable. HTML elements inherit their font size from their re­spec­tive parent elements. A technical guide value, such as the display size of a device or the default value in a web browser, could also serve as ref­er­ences for relative font size.

Relative mea­sure­ments:

Unit CSS notation De­scrip­tion
Per­cent­age % The % mea­sure­ment gives the font size as a per­cent­age of the inherited font size. With an inherited font size of 16 px, a font-size of 75% cor­re­sponds to a font size of 12 px.
em (font height) em The mea­sure­ment em also stands in relation to the parent element. A mea­sure­ment of 1 em means 100% of the inherited font size. If a font size of 20 px is defined, that cor­re­sponds to a value of 0.8 – for example, a font size of 80% or 16 px. If no font size is defined for the parent element, then the default font size of the device is used.
x-height ex The reference value for the ex mea­sure­ment is the height of the lowercase letter x in the chosen font. If the chosen font doesn’t have a defined x height, then 1 ex = 0.5 em.
Root-em rem The mea­sure­ment rem refers to the root element of a document (e.g. the HTML element). 1 rem rep­re­sents 100% of the font size de­ter­mined for the root element.
Viewport width vw The vw mea­sure­ment is based on the width of the display (viewport) of a device. This means that 1 vw = 1% of the viewport width.
Viewport height vh The mea­sure­ment vh is based on the height of the display (viewport) of a device. This means that 1 vh = 1% of the viewport height.

Font size can also be defined using absolute and relative keywords. The default font size of the browser can be used as a guide (it cor­re­sponds to font-size: medium).

Absolute keywords:

Absolute De­scrip­tion Example
xx-small tiny 9 px
x-small very small 10 px
small small 13 px
medium medium (default browser font size) 16 px
large large 19 px
x-large very large 24 px
xx-large huge 32 px

Relative keywords:

Relative De­scrip­tion
smaller The current element is displayed smaller than the parent element.
larger The current element is displayed larger than the parent element.

To guarantee an optimal display of the font size on different user devices, it’s rec­om­mend­ed to use relative mea­sure­ments such as em or %. If the output needs to be absolute, px is the choice of mea­sure­ment for most web designers.

The basic structure of the font size for­mat­ting via CSS cor­re­sponds to the following code example:

.content {
            font-size: 19px;
    }
    <h2 class=“content”>Example text</h2>

The following graphic shows the three different font sizes 16 px, 19 px, and 21 px next to each other.

line-height

The CSS property line-height is used to define the amount of space above and below text elements in a paragraph. The same mea­sure­ments apply as for font-size, where per­cent­ages refer to the font-size of the re­spec­tive text. Al­ter­na­tive­ly, you can specify the line-height in numbers with no unit of mea­sure­ment. Other possible values are normal (standard settings) and inherit (cor­re­spond­ing to the parent element). A line-height of 1.5, for example, cor­re­sponds to a line height of 150% percent of the re­spec­tive font size, or 1.5 em.

.content {
    line-height: 1.5;
}
<p class="content">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</p>

The following graphic shows text blocks with a line height of 100, 120, and 150 percent next to each other:

font-weight

The CSS property font-weight defines the stroke width of a text element. Web designers use these to display areas of texts as fatter than normal. Absolute or relative values of the parent element can be given.

Absolute value De­scrip­tion
100 extra thin
200 very thin
300 thin
400 normal (standard settings)
500 medium
600 half-thick
700 thick
800 very thick
900 extra thick
normal normal width (same as 400 value)
bold thick (same as 700 value)

Absolute values for the font-weight property are displayed dif­fer­ent­ly depending on the font. The problem is that different font thick­ness­es are necessary for different font styles. Normally, fonts are only available in normal, italic, bold, and italic + bold. If only two font thick­ness­es are defined, then the browser takes the thinner font for the value 100, 200, 300, 400, and 500, and the thicker for the higher values. Number values are only relevant for web fonts. As a rule, two different font thick­ness­es are enough: normal and bold.

.content {
    font-weight: normal;
}
.content {
    font-weight: bold;
}

Relative values for the CSS property font-weight define the font thickness of a text element in com­par­i­son to the inherited font thickness of the parent element.

Relative value De­scrip­tion
bolder bolder than the parent element
lighter thinner than the parent element

Text for­mat­ting

In addition to for­mat­ting the font, there are multiple options available in CSS for various text for­mat­ting prop­er­ties. These enable you to make settings for text alignment, as well as for the distance between char­ac­ters and words, or to provide dec­o­ra­tions for text elements. Important prop­er­ties of text for­mat­ting are:

  • text-align
  • hyphens
  • word-spacing
  • letter-spacing
  • text-indent
  • text-dec­o­ra­tion
  • text-transform

text-align

The CSS property text-align is used to align text and inline elements: elements that are contained in the text flow, such as images or buttons. Standard values are left (left-aligned), right (right-aligned), center (centered), justify (block set), or inherit (like parent element). The following code achieves a centered alignment of the example text:

.content {
    text-align: center;
}
<p class="content">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</p>

Other design options are shown in the following graphic:

Other values for the text-align property define the text alignment in relation to the direction of the text.

Values for the relative text alignment De­scrip­tion
start Text is aligned to the side on which it begins. For text direction that goes from left to right { direction: ltr; }, the value start means left. For a right to left text direction { direction: rtl; ,} the value start means right.
end Text is aligned to the side on which it ends. For text direction from left to right { direction: ltr; }, the value end means right. For a right to left text direction { direction: rtl; }, the value end means left.

Generally, start serves as the standard value.

All popular browsers au­to­mat­i­cal­ly display the last row in a block set as left-aligned. If this isn’t what you want, you can format it sep­a­rate­ly with the CSS propert text-align-last. The possible values cor­re­spond to those of the text-align property.

hyphens

With the hyphens property, CSS3 offers the pos­si­bil­i­ty to set up an automatic syllable sep­a­ra­tion. The stylesheet language has the following available values for the hyphens property:

Value for hyphens property De­scrip­tion
manual Manual syllable sep­a­ra­tion: Soft sep­a­ra­tors (&shy or &#173) are con­sid­ered for syllable sep­a­ra­tion (standard value for hyphens).
none No syllable sep­a­ra­tion: Soft sep­a­ra­tors (&shy or &#173) are not con­sid­ered for syllable sep­a­ra­tion. The link breaks are only inserted for space.
auto Automatic syllable sep­a­ra­tion: The word sep­a­ra­tion is carried out according to the rules of the language defined by the HTML attribute lang.
inherit The settings cor­re­spond to those of the parent element.
Tip

The CSS property hyphens is not currently supported by all web browsers.

word-spacing

The CSS property word-spacing controls the internal word spacing of a text element. Website operators have the option to define the distances between words by size. Displayed mea­sure­ments are available under font-size – with the exception of per­cent­age spec­i­fi­ca­tions. Other possible values for the word-spacing property are normal (standard settings) and inherit (cor­re­spond­ing to the parent element).

The following code example defines a word spacing of 2 em. This adds to the default word spacing (word-spacing: 0; is the standard value).

.content {
    word-spacing: 2em;
}
<p class="content">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</p>

letter-spacing

If the spacing of the letters is supposed to be defined instead of the spacing of the words, then the CSS property letter-spacing is used. Here too, sizes (with the exception of per­cent­age spec­i­fi­ca­tion) as well as the values normal and inherit, are available.

The following code example shows a text selection in which one of the words has a letter spacing of 1 em. The class special-content in the HTML source code is given the span element.

.special-content {
    letter-spacing: 1em;
}
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna <span class="special-content">aliquyam</span> erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</p>

text-indent

With the CSS property text-indent, you have the option to define in­den­ta­tions which are only applied to the first line of a paragraph. Possible values are positive and negative, as well as per­cent­ages in relation to the width of the re­spec­tive text blocks.

The following code example defines an in­den­ta­tion for the first line of 5 percent:

.content {
    text-indent: 5%;
}
<p class="content"> Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem.</p>

To define hanging para­graphs, the text-indent property is given a negative value.

text-dec­o­ra­tion

The CSS property text-dec­o­ra­tion provides text elements with dec­o­ra­tions, such as un­der­lines. Possible values are:

Values for the text-dec­o­ra­tion property De­scrip­tion
none No text dec­o­ra­tion.
underline Every line of the high­light­ed text selection is un­der­lined.
overline A line is displayed over every line of the high­light­ed text selection.
line-through Every line of the high­light­ed text selection is struck through.
inherit The text dec­o­ra­tion cor­re­sponds to that of the parent element.

The following code example defines un­der­lines for the selected word groups within the text selection. The class content-underline in the HTML source text is given the span element.

.content-underline {
    text-decoration: underline;
}
<p>Nullam quis ante. Etiam sit amet orci eget eros <span class="content-underline">faucibus tincidunt</span>. Duis leo. Sed <span class="content-underline">fringilla mauris sit</span> amet nibh. Donec sodales sagittis magna.</p>

text-transform

The property text-transform makes it possible to carry out text trans­for­ma­tions via CSS. Here, text areas can be displayed is ma­jus­cules (uppercase letters) or mi­nus­cules (lowercase letters) without needing to adapt the text base. The property enables the following trans­for­ma­tions:

Value for text-transform property De­scrip­tion
cap­i­tal­ize The first letter in every word is displayed in uppercase.
uppercase The entire text selection is displayed in uppercase.
lowercase The entire text selection is displayed in lowercase.
none No trans­for­ma­tion.
inherit The trans­for­ma­tion cor­re­sponds to the parent element.

If the beginning letters of a selection are displayed as uppercase, re­gard­less of the source text, the following for­mat­ting is used:

.content {
    text-transform: capitalize;
}
<p class="content">Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.</p>

The following graphic shows the CSS text trans­for­ma­tions in com­par­i­son.

Font and back­ground colors

When choosing font and back­ground colors, web designers generally utilize the pre­vi­ous­ly es­tab­lished color codes in decimal or hexa­dec­i­mal notation. Here, the CSS prop­er­ties color and back­ground-color are used. You can also integrate a back­ground image using the back­ground-image property.

color

The CSS property color offers for­mat­ting for font colors. Common values are colors in the form of RGB values, hexa­dec­i­mal codes, or HSL data. The trans­par­ent value enables elements to be displayed with little vis­i­bil­i­ty. According to W3C rec­om­men­da­tions, the keyword trans­par­ent has the value rgba(0,0,0,0) (trans­par­ent black).

The following code example shows color for­mat­ting using a hexa­dec­i­mal color code:

.content {
    font-family: Arial;
    font-size: 5em;
    color: #d82451;
}
<p class="content">Example text</p>

back­ground-color

The CSS property back­ground-color is used if an element is to be assigned a back­ground color. The possible values cor­re­spond to those of the color property.

The following code examples shows a for­mat­ting of font and back­ground color:

.content {
    font-family: Arial;
    font-size: 5em;
    color: #d82451;
    background-color: #24d8ab;
}
<p class="content">Beispieltext</p>

The for­mat­ting instructs the web browser to display all text elements of the content class claret red (#d82451) and to make the back­ground turquoise green (#24d8ab).

back­ground-image

Instead of setting a back­ground color, you can also set an image as the back­ground for an element. Web designers use the property back­ground-image, which contains the path to the graphic as the value according to the following notation:

.content {
    background-image: 
        url (path to image file);
}

Instead of back­ground-image or back­ground-color, you can also use the ab­bre­vi­at­ed form back­ground.

CSS3 also offers the pos­si­bil­i­ty to define color gradients as the back­ground. Possible values are the functions linear-gradient(), radial-gradient(), repeating-linear-gradient(), and repeating-radial-gradient().

CSS color gradient De­scrip­tion
linear-gradient() The function linear-gradient() generates a linear color gradient.
radial-gradient() The function radial-gradient() generates a radial color gradient.
repeating-linear-gradient() The function repeating-linear-gradient() generates a repeating linear color gradient.
repeating-radial-gradient() The function repeating-radial-gradient() generates a repeating radial color gradient.

More about color gradients can be found on the W3C website. In our CSS in­tro­duc­tion, we limit our examples to the function linear-gradient(). If an element is to be stored with a linear color gradient, use the linear-gradient() function as the value for the back­ground property. This expects at least two color in­di­ca­tions as arguments. Which notation is used to define the colors is up to the web designer. For the sake of clarity, we use the color key words for our example.

.content {
    width: 400px;  
    height: 400px;  
    background: linear-gradient( green, yellow );
}

A web browser displays the linear-gradient( green, yellow); according to the default setting as a vertical color gradient with equiv­a­lent green and yellow sections:

Web designers have the option to in­di­vid­u­al­ly determine the direction of the color gradient and its position. The gradient direction is defined either as an angle measure or by spec­i­fy­ing an edge (to top, to bottom, to left, to right) or to a corner (to right top, to right bottom, to left bottom, to left top).

.rahmen {
    width: 400px;
    height: 400px;
    background: linear-gradient( to left top , green, yellow );
}

A trend in­di­ca­tion as an angle measure is made clockwise from the standard value (to bottom). Possible mea­sure­ments are deg (degree), grad (gradian), and rad (radian). In this case:

to bottom = 180deg = 200grad = 3.1416rad

The position of a color gradient is de­ter­mined by the color stop in­di­ca­tors. These are usually indicated on the gradient axis with a value of 0 to 100 percent.

The standard positions of colors in a two-color gradient are 0 percent and 100 percent. The area between these is cal­cu­lat­ed by the browser as a color gradient and displayed in in­ter­me­di­ate tones.

Color stops make it possible to start or end the color gradient at any selected position on the gradient axis.

The following graphic shows two color gradients with different color stop data:

back­ground: linear-gradient( 90deg, red 0%, yellow 100% );

back­ground: linear-gradient( 90deg, red 25%, yellow 75% );

The first example shows a color gradient from 0 to 100 percent. In the second example, the gradient begins at 25 percent and ends at 75 percent.

In CSS color gradients, you can combine as many colors as you want – with trans­paren­cy levels as desired.

Borders

CSS also allows you to frame HTML elements with a border. This is es­pe­cial­ly rec­om­mend­ed for block-level elements, such as headings (h1-6), para­graphs (p), div elements, or tables that are contained within the body element. Without other for­mat­ting, the content blocks extend over the entire available width and arrange them­selves one below the other. Some block-level elements such as <p> or <h1> have a default margin setting.

Inline elements like <b>, <i>, <a>, or <span> help to dis­tin­guish between the block-level elements. Inline elements occur ex­clu­sive­ly within block-level elements. The width of an inline element is de­ter­mined solely by its own content.

If a border contains an entire block-level or inline element, then the borders property is used. Al­ter­na­tive­ly, you can define the border design for each page of an element in­di­vid­u­al­ly.

Border prop­er­ties De­scrip­tion
border Defines the border design for all pages of an element.
border-top Defines the prop­er­ties of the top border.
border-right Defines the prop­er­ties of the right border.
border-bottom Defines the prop­er­ties of the bottom border.
border-left Defines the prop­er­ties of the left border.

Both the border property and the prop­er­ties for in­di­vid­ual border edge can be specified with respect to the border-style, the border-width, and the border-color. Cor­re­spond­ing values are notated in the following pattern, behind the property and separated with spaces:

.content {
    border: style width color;
}
.content {
    border: solid 4px #ff0000;
}

The border-radius property also gives the option to round the border edges.

border-style

With the choice of border styles, you can define a dec­o­ra­tive frame for the block-level or inline element in question. Some border styles only come into play if an adequate frame width is selected.

Possible border style values De­scrip­tion
none No border.
hidden Displays no border and sup­press­es it with the neigh­bor­ing table cells.
dotted Defines a dotted border.
dashed Defines a dashed border.
solid Defines a solid border.
double Defines a double border.
groove, ridge, inset, outset These values implement different 3D effects.

The following graphic shows the CSS border styles in com­par­i­son:

Spec­i­fy­ing the border style is oblig­a­tory, and if no border style is given then the border isn’t displayed by the web browser – even if there are values for frame width or frame colors.

border-width

The border width defines the thickness of the border’s lines.

Possible border width values De­scrip­tion
Length spec­i­fi­ca­tion The size spec­i­fi­ca­tion of the border width is de­ter­mined using the units described under font-size. The border width can’t be specified as a per­cent­age.
thin Thin width
medium Medium width
thick Thick width

border-color

The color settings for the border-color property cor­re­spond to the prop­er­ties color and back­ground-color.

Possible border color values De­scrip­tion
Color spec­i­fi­ca­tion Color spec­i­fi­ca­tions for borders can be given in keywords (i.e. red), as HEX values or as RGB or HSL spec­i­fi­ca­tions.
trans­par­ent Defines the border as trans­par­ent.

The following code example combines the border property with for­mat­ting for font and back­ground colors. This rule set is defined in the CSS document for the border class:

.border {
    font-family: Arial;
    font-size: 5em;
    color: #d82451;
    background-color: #24d8ab;
    border: 10px ridge #d82451;
}

To apply the for­mat­ting, the CSS class border is trans­ferred to the <p> element in the HTML source code using the class attribute.

<p class=“border”>Example text</p>

A web browser displays such for­mat­ting as follows:

border-radius

The border-radius property allows you to round the corners of a border, either cir­cu­lar­ly or el­lip­ti­cal­ly. A possible back­ground is trimmed along the defined curve – even when an element doesn’t have a border. Cleverly used, simple geometric forms can also be drawn with border-radius.

Possible values for the border property are up to four size de­c­la­ra­tions, each for a re­spec­tive border corner. As­sign­ment can be by one, two, three, or four values.

Values for the border-radius property De­scrip­tion
One value defined The value is applied to all four corners.
Two values defined The first value defines the top left and bottom right corners. The second value defines the top right and bottom left corners.
Three values defined The first value defines the top left corner. The second value defines the top right and bottom left corners. The third value defines the bottom right corner.
Four values defined Every corner is defined by its own value. The order is applied in a clockwise direction: top left, top right, bottom right, bottom left.

The in­di­vid­ual values for the border radius are noted by sep­a­rat­ing spaces behind the border-radius property. The de­c­la­ra­tions are given in a pattern that looks as follows (the number values here are just examples):

border-radius: 4em 2em 3em 1em;

The border-radius property can be defined in the same rule set as the border property or in a separate class.

The following rule set defines a border with border-radius of 2 em:

.border {
    height: 100px;
    width: 600px;
    border: solid 10px #d82451;
    border-radius: 2em;
}

You can also define different values for each of the four corners:

.border {
    height: 100px;
    width: 600px;
    border: solid 10px #d82451;
    border-radius: 2em 1em 3em 4em;
}

In both cases, the corners of the border are cir­cu­lar­ly rounded. If you want the rounding to be el­lip­ti­cal, then two values would be required for each corner. The de­c­la­ra­tion of an el­lip­ti­cal­ly rounded border can contain up to eight values:

border-radius: 1em 4em 1em 4em / 4em 1em 4em 1em;

The values before the slash (/) define the radius of the hor­i­zon­tal semi-axis of the ellipse, and the values after the slash define the radius of the vertical semi-axis.

.border {
    height: 100px;
    width: 600px;
    border: solid 10px #d82451;
    border-radius: 1em 4em / 4em 1em;
}

Potential back­grounds are au­to­mat­i­cal­ly altered along the curve.

.border {
    height: 100px;
    width: 600px;
    border: solid 10px #d82451;
    border-radius: 2em; 
    background-color: #24d8ab;
}

This goes for back­ground colors as well as back­ground images, but not for text elements.

The CSS box model

To align text elements, graphics, and other design elements on a website, a CSS strategy based on the for­mat­ting of the rec­tan­gu­lar surfaces is used, created by the various block-level and inline elements. This is called the CSS box model.

Every HTML element is rendered as a rec­tan­gu­lar area in the frontend display of a website – the so-called box. The char­ac­ter­is­tics of such boxes, their flow and extent, determine the design of a website. As a result, every website can more or less be viewed as an arrange­ment of various boxes.

The po­si­tion­ing of in­di­vid­ual boxes is defined by the document flow. This follows a stan­dard­ized pattern: As long as no other for­mat­ting is present, every element can be displayed as far left as possible – beginning with the first element in the HTML source text. All following elements are arranged next to them, on the right. If there is no more room, the next box can be placed into a new row.

CSS dif­fer­en­ti­ates between two types of boxes:

  • Block boxes: Block boxes are comprised of block-level elements (e.g. p or div). As a rule, web browsers display these so that their width cor­re­sponds to the overall width of the parent elements. It is also paragraph-gen­er­at­ing. Following elements are au­to­mat­i­cal­ly placed in the next line. The height of a block box fixes itself based on the content of the elements or the potential for­mat­ting. Block boxes can contain not only other block-level elements, but also inline elements.
  • Inline boxes: Inline boxes are comprised of the internal inline elements (e.g. b, i or span) of a block box, and so are not paragraph-gen­er­at­ing. Width and height of an inline element are fixed ex­clu­sive­ly based on its own content.

The following diagrams il­lus­trate the document flow of block and inline boxes:

If no other for­mat­ting is in place, then block boxes are displayed with a maximum width, re­gard­less of their content. Every box begins a new paragraph and extends over the total width of the parent element. In the example, this is rec­og­nized with the gray border. It should be noted that some block-level elements, such as <p>, are rendered by web browsers with an automatic default margin.

Inline boxes within a block-box don’t begin a new paragraph, and are instead displayed ‘inline’ with the document flow.

The example shows an inline box outlined in turquoise, con­tain­ing the word group “con­sectetuer adip­isc­ing elit”.

Based on the paragraph-gen­er­at­ing functions, the layout of a website primarily results from the for­mat­ting of block boxes. It doesn’t nec­es­sar­i­ly have to revolve around the content elements, such as headline or text para­graphs. Often, the empty semantic HTML elements like <div> are used to group other elements and create a set that can be formatted via CSS.

The for­mat­ting is carried out using CSS box model. According to this model, each HTML element can be described by four nested boxes, which can be adapted in­de­pen­dent­ly to fit the desired design idea. These are dif­fer­en­ti­at­ed between Content-Box, Padding-Box, Border-Box, and Margin-Box.

Box model levels De­scrip­tion
Content (Content-Box) The Content-Box rep­re­sents an area whose extent is de­ter­mined by the text range or di­men­sions of a graphic. With block-level elements, the height and width can be in­di­vid­u­al­ly defined using the height and width prop­er­ties. For inline elements, for­mat­ting of this type isn’t available.
Internal space (Padding-Box) The Padding-Box defines the space between the Content-Box and the Border-Box.
Border (Border-Box) The Border-Box defines the border.
External space (Margin-Box) The Margin-Box defines the space between the current elements and their parent elements or neigh­bor­ing elements. As opposed to padding and border, the margin property can also display negative values.

If all four edges of a box are formatted the same, then the padding, border, and margin prop­er­ties are used. Internal and external space, as well as borders, are formatted sep­a­rate­ly for every side of a CSS box. The re­spec­tive prop­er­ties are shown in the following table:

  Internal space Border External space
upper padding-top border-top margin-top
lower padding-bottom border-bottom margin-bottom
left padding-left border-left margin-left
right padding-right border-right margin-right

Possible values for the listed prop­er­ties are size and inherit (cor­re­spond­ing to the parent element). External space can be defined with the auto value.

The following graphic shows the schematic structure of a CSS box:

Use of the CSS box model

The CSS box model can be clarified by adding the in­di­vid­ual levels to the content box step-by-step. The starting point is a short text selection, which in this example is formatted using the class selector content:

<p class="content">At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctusest Lorem ipsum dolor sit amet.</p>

The following rule set gives the content box di­men­sions of 150 px x 150 px. Further for­mat­ting defines a black font (color: #000000;) on a white back­ground (back­ground-color: #ffffff;). The text in the block set is also aligned (text-align: justify;):

.content {
     height: 150px;
     width: 150px;
     color: #000000;
     text-align: justify;
    background-color: #ffffff;
}

When applied to the text selection, these design in­struc­tions lead to the following rep­re­sen­ta­tion in the web browser:

According to the document flow, the text selection appears in the upper left corner of its parent element – displayed here as the gray back­ground field. The text and the white back­ground begin without any space on the left side of the browser window and fill the entire available area (150 px x 150 px). The white back­ground ends directly with the text body.

But a design like this isn’t very pretty, and makes it difficult to read. The padding property enables a web design to define an internal space to separate text elements from sur­round­ing design elements.

.content {
     height: 150px;
     width: 150px;
    color: #000000;
    background-color: #ffffff;
    text-align: justify;
    padding: 10px; 
}

Adding the de­c­la­ra­tion padding: 20px to a rule set achieves the following changes in the frontend display:

The web browser adds an internal space of 20 px to all four sides of the content box. The element now measures 190 px x 190 px. A further design element is the border.

.content {
     height: 150px;
     width: 150px;
     color: #000000;
     background-color: #ffffff;
     text-align: justify;
     padding: 10px;
    border: 5px solid #d82451;
}

In the example code, the border property is given the value 5px solid #d82451. In the browser view, this for­mat­ting results in a solid, claret red border that surrounds the padding box.

A border is offset from the content by the padding value.

According to the natural document flow, a box formatted in this way fits without any space from the upper left corner to the parent element. The margin property allows you to loosen up the design of a website by using external space.

The cor­re­spond­ing de­c­la­ra­tion is simply added to the existing rule set:

.content {
    height: 150px;
    width: 150px;
    color: #000000;
    background-color: #ffffff;
    text-align: justify;
    padding: 20px;
    border: 5px solid #d82451;
    margin: 40px;
}

In the web browser, an external space like this of 40 px would look as follows:

The block box <p> is now freely set within the parent element.

Mea­sure­ments can also be provided in the margin property with the auto value. In this case, the box is au­to­mat­i­cal­ly hor­i­zon­tal­ly centered within the parent element. The auto value doesn’t work in the vertical direction.

.content {
    width: 150px;
    color: #000000;
    background-color: #ffffff;
    text-align: justify;
    padding: 20px;
    border: 5px solid #d82451;
    margin: auto; 
}

Cal­cu­lat­ing the height and width of a CSS box

The space re­quire­ment of a CSS box is de­ter­mined once all values of the relevant areas of the box have been added. The follow cal­cu­la­tions are used:

If the element measures 200 px x 200 px, then the required space is 280 px x 280 px.

Float

If the box being formatted is a block box, then all following boxes are au­to­mat­i­cal­ly moved to the next line according the document flow.

In practice, the automatic line break after a block box is not always desired and can be prevented with the float property. This removes block boxes from the normal document flow and instead puts them in the desired position. According to CSS spec­i­fi­ca­tions, float accepts four values:

Values for the float property De­scrip­tion
none No element shift takes place. The value float: none; is the standard value of a CSS box.
left The block box shifts to the left inner edge of the parent element.
right The block box shifts to the right inner edge of the parent element.
inherit The float value cor­re­sponds to the parent element.

A box with float for­mat­ting is called a float.

If multiple floats meet one another, they are arranged either from left to right (float: left) or right to left (float: right), in the order in which they appear in the HTML source code.

The following code example shows a .content rule set that includes a float property.

.content {
    height: 150px;
    width: 150px;
    color: #000000;
    background-color: #ffffff;
    text-align: justify;
    padding: 20px;
    border: 5px solid #d82451;
    margin: 40px; 
    float: left; 
}

If this is applied to two HTML elements, then they are taken out of the document flow and aligned together to the left.

<p class="content">At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctusest Lorem ipsum dolor sit amet.</p>
<p class="content">Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus.</p>

The large spacing is obtained by adding together the external spacing of both boxes (each margin in 40 px). Without a float, the external margins of adjacent elements would collide.

If the total width of the suc­ces­sive floats is larger than the width of the parent element, then the following elements coming from the parent element are placed into the next line.

This rule doesn’t apply to the first float. If this is bigger than its parent element, then it extends outside the parent element bound­aries.

Another option for using the float property is cus­tomiz­ing the po­si­tion­ing in­for­ma­tion, in order to lift CSS boxes out of the natural document flow.

Po­si­tion­ing

The CSS property property serves to remove a box from the document flow and place it in a specified location on the website. Other boxes – whether tied to the document flow or po­si­tioned otherwise – have no influence on the po­si­tion­ing of boxes formatted in this way.

The position property has the five possible values of absolute, fixed, relative, static, and sticky, and is specified using the left, right, top, and bottom prop­er­ties, as well as their values as mea­sure­ments. In general, two values are enough to specify a position (e.g. top and left).

Values for the position property De­scrip­tion
absolute The box is detached from the document flow and po­si­tioned where defined by the top, bottom, left and right prop­er­ties. The in­for­ma­tion is given in relation to the next highest element also specified using the position property. If such an element doesn’t exist, then the root element <html> is used as the reference point. Boxes with the position: absolute de­c­la­ra­tion have no influence on the position of other elements, and either su­per­im­pose or overlay them.
relative When the position: relative de­c­la­ra­tion is used, the box remains in­te­grat­ed in the natural document flow, but can be moved relative to this using the po­si­tion­ing in­for­ma­tion top, bottom, left, and right. The re­spec­tive box is po­si­tioned on its own. Existing and following elements in the flow behave as if the box had not been moved.
fixed When a box is placed using position: fixed, the position is defined in relation to the viewport. A box fixed in this way appears in the same place on the screen – even if a visitor scrolls through the page. Nav­i­ga­tion elements like menus or stopper buttons (i.e. “Back to Home”) can be attached to the user’s view like this.
static This box occupies a natural position in the text flow. If the position: static de­c­la­ra­tion is chosen, then the position spec­i­fi­ca­tions top, bottom, left, and right are voided. The static value is the standard value for the position property.
sticky This position is cal­cu­lat­ed according to the normal document flow, and behaves like an element with the position: relative de­c­la­ra­tion, as long as it’s within the viewport. But if it’s close to dis­ap­pear­ing form the display area, then it will break out of the document flow and ‘stick’ to the position defined by the web designed while the visitor is scrolling. The sticky value can also be used in com­bi­na­tion with relative and fixed.

Absolute po­si­tion­ing

The following rule set contains absolute po­si­tion­ing spec­i­fi­ca­tions for red, blue, and green CSS boxes within the back­ground parent element.

.background {
    height: 500px; 
    width: 500px;
    border: solid grey 
}
.red {
    height: 150px;
    width: 150px;
    background-color: rgba(255,0,0,0.5);
    position: absolute;
    top: 100px;
    left: 100px;
}
.blue {
    height: 150px;
    width: 150px;
    background-color: rgba(0,0,255,0.5);
    position: absolute;
    top: 150px;
    left: 150px;
}
.green {
    height: 150px;
    width: 150px;
    background-color: rgba(0,255,0,0.5);
    position: absolute;
    top: 200px;
    left: 200px;
}

The red, blue, and green content boxes are formatted with half-trans­par­ent, 150 px x 150 px areas. The back­ground content box is 500 px x 500 px and has a gray border.

The design in­struc­tions are in­te­grat­ed via classes in the HTML code.

<div class="background">
    <p class="red"> </p>
    <p class="blue"> </p>
    <p class="green"> </p>
</div>

The browser view shows the different positions of the <p> boxes within the <div> element. The elements are offset to the right by 50 px. The trans­par­ent coloring clarifies the pos­si­bil­i­ty of an overlap in absolute po­si­tion­ing.

Relative po­si­tion­ing

With relative po­si­tion­ing, the alignment of in­di­vid­ual boxes takes place based on the normal document flow. Block-level elements without float for­mat­ting are displayed beneath one another.

The external spacing above the elements cor­re­sponds to the default value for <p> elements.

To align a box out of its position in the document flow, the cor­re­spond­ing rule set is extended by the position: relative de­c­la­ra­tion, as well as the desired position data.

The following code block uses the blue box as an example:

.content2 {
    height: 150px;
    width: 150px;
    background-color: rgba(0,0,255,0.5);
    position: relative;
    left: 50px;
}

The design in­struc­tion position: relative with the position spec­i­fi­ca­tion left: 50px instructs the browser view to displace the blue box by 50 px to the left.

The relative po­si­tion­ing can also be applied to floated elements.

.content2 {
     height: 150px;
     width: 150px;
     background-color: rgba(0,0,255,0.5);
     position: relative;
    top: 50px;
    float: left;
}

Fixed CSS boxes

The ori­en­ta­tion of fixed boxes is similar to the absolute po­si­tion­ing of elements removed from the document flow. All po­si­tion­ing in­for­ma­tion is related to the viewport of the user.

The following rule set instructs a web browser to fix a small red box in the upper left corner of the viewport.

.content1 {
    height: 50px;
    width: 150px;
    background-color: rgba(255,0,0,0.5);
    position: fixed;
    bottom: 10px;
    left: 15px;
}

In any case, the red box always remains at the defined position of the browser window (bottom: 10px; left: 15px;), even if other elements, such as the blue text box, allow you to scroll down on the web page.

From beginners to pro­fes­sion­als

The goal of our tutorial was to il­lus­trate the pos­si­bil­i­ties of CSS for beginners. A short crash course is obviously not enough to describe all functions of the stylesheet language in detail. If your interest in CSS goes beyond the for­mat­ting discussed here, we recommend the very detailed wiki W3 for further research, as well as the Mozilla Developer Network. We’ve also compiled a selection of useful CSS tricks for advanced users in a more detailed guide article on the topic.

Go to Main Menu