How to learn CSS coding for beginners
CSS is used to define the look and visual design of web pages. With Cascading Style Sheets, design is separated from content, resulting in a clean and flexible structure. In this tutorial, you’ll learn how CSS coding allows you to precisely control the layout, colours, and typography of your website.
Separating content and presentation
In combination with HTML, CSS is used to separate content from presentation.
Hypertext Markup Language (HTML) is used to enrich text documents with information that provides semantic structure for individual text elements. This markup language forms the foundation of every website through its HTML code. It defines which HTML elements a document consists of such as <body>, <header>, and <footer>, and how the content should be interpreted, for example as a heading <h1> or a text paragraph <p>.
Originally, HTML also included rudimentary design instructions. However, with HTML5, these are considered outdated and should no longer be used. Instead, the stylesheet language CSS (Cascading Style Sheets) is used to handle presentation rules separately.
- Intuitive website builder with AI assistance
- Create captivating images and texts in seconds
- Domain, SSL and email included
What is CSS?
Like HTML, CSS is also written in text form. This can be done directly in the HTML document (inline for each document or once in the HTML head). Typically, however, web designers incorporate separate CSS documents to format web pages. The result is a clear source code, where redundant design instructions are avoided by referencing separate stylesheets. The fewer the repetitions, the leaner the source code.
If design adjustments are needed, they are made in the central CSS files. This eliminates the need to review and update each individual HTML document separately. As a living standard, CSS is continuously developed by the World Wide Web Consortium (W3C).
Basic structure of CSS syntax
The primary task of CSS is to define the design of a website. For this purpose, properties with certain values are assigned to the underlying HTML elements using the stylesheet language. The basic structure of a design instruction follows this pattern:
Selector { Declaration }cssThe selector identifies the HTML element to which a design rule applies. The declaration itself is defined by a property–value pair enclosed in curly braces, with each declaration ending in a semicolon.
HTML elements { property: value; }cssAccording to this pattern, a text colour like red can be assigned to a headline, for example:
h2 { color: red; }cssWeb designers have the option to assign a single property to the selector or define comprehensive rule sets that include detailed design instructions. For clarity, a writing style has been established where all properties of a rule set are written on separate lines:
selector {
property1: value;
property2: value;
property3: value;
}cssIn practice, a set of properties might look like this:
h2 {
color: #ff0000;
font-family: Helvetica, sans-serif;
font-size: 19px;
font-weight: bold;
text-align: center;
}cssThe selector identifies the HTML element to which a design rule applies. The declaration itself is defined by a property–value pair enclosed in curly braces, with each declaration ending in a semicolon:
selector1, selector2 { declaration }cssCSS selectors
CSS offers a wide range of selectors that make it possible to target and apply styling rules with precision. For beginners, it’s enough to focus on type, class, ID, and universal selectors. Keep in mind that CSS is case-sensitive, so correct capitalisation is important.
| Type of selector | CSS notation | Description | Specificity |
|---|---|---|---|
| Type selector | HTML Element (e.g., h2)
|
A type selector matches the name of the element it refers to. Styles are applied to all HTML elements of the same type. | 1 |
| Class selector | .example
|
A class selector targets all elements of a specific class. Class selectors are created with a dot (.) and any class name: .example - classes are assigned to HTML elements via the class attribute (class="example").
|
10 |
| ID selector | #example
|
An ID selector targets a single element with a unique ID. It is integrated into the HTML source code using the id attribute (id="example").
|
100 |
| Universal selector | *
|
The universal selector asterisk (*) targets all HTML elements in a document.
|
0 |
When multiple rules apply to the same element, the selector’s specificity determines which rule takes precedence. Each type of selector carries a defined weight that is used to calculate its overall specificity.
Type selector
The use of various CSS selectors can be illustrated with examples. The following code shows the type selector h2 with a declaration:
h2 {
color: #305796;
font-family: Helvetica, sans-serif;
}cssThe formatting applies to all HTML elements of type h2.
Class selector
Alternatively, CSS formatting can be done using a class selector. This allows designers to apply the same styling instructions to HTML elements, regardless of their specific type.
.content {
color: #ff0000;
font-family: Helvetica, sans-serif;
}cssThe formatting applies to all HTML elements that are assigned the .content class. This assignment is defined in the HTML code as follows:
<p class="special-text">Example text</p>htmlIn HTML, class names are written without a dot.
ID selector
If a style rule should apply to only a single element in the HTML source code, an ID selector is appropriate. The following example shows the formatting of a navigation area:
#navigation {
font-family: Helvetica, sans-serif;
background-color: #8ad8d4;
border: 2px solid #448278;
}cssThe formatting is assigned in the HTML source code without using a hashtag.
<div id="navigation">
<ul>
<li><a href="index.htm">Home</a></li>
<li><a href="impressum.htm">Legal Notice</a></li>
</ul>
</div>htmlThe advantage of ID selectors is that it is immediately apparent which sections in the source code are unique areas.
Universal selector
If a styling rule is meant to apply to all elements in an HTML document, the asterisk (*) is used:
* {
font-family: Helvetica, sans-serif;
}cssAll text elements are displayed by the web browser in the Helvetica font.
How to integrate CSS into HTML
For a browser to apply CSS formatting, the styling instructions must be linked to the HTML source code. Users have three options for doing this:
- Direct integration of the CSS declaration in HTML tags
- The CSS markup in the HTML head
- The reference to a separate stylesheet
The latter solution is considered best practice. In real-world use, stylesheets are typically created as external text files and then linked to the document.
CSS declaration in HTML tags
If a CSS declaration is meant to format a single point in the source code, it can be included directly in the opening tag of the HTML element to which the styling instruction applies using the style attribute. This is known as an ‘inline style’.
<h2 style="color: red;">Subheading</h2>htmlThe main benefit is that no separate stylesheet is required, and because no selector is used, this type of styling has a very high priority (value 1000). However, once many rules are applied, this approach quickly becomes cumbersome and leads to unnecessary repetition.
CSS markup in the HTML head
If the same styling rule is meant to be applied multiple times within an HTML document for the same element, such as all h2 elements on a page, defining the style directly in the HTML tag is inefficient. Instead, it is recommended to define the styling once in the document’s HTML head using the style element.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
h2 {
color: #ff0000;
font-family: 'Helvetica Neue', sans-serif;
font-size: 19px;
font-weight: bold;
text-align: center;
}
</style>
</head>
<body>
<h2>Subheading1</h2>
[…]
<h2>Subheading2</h2>
[…]
</body>
</html>htmlThe rule set within the style element is automatically applied to all subsequent h2 elements. If the h2 element is also meant to be used on other web pages within the same online project using the design rules defined here, the rule can simply be placed in a central CSS file.
Reference to a separate stylesheet
When styling instructions are defined in a separate stylesheet, it must be included in the underlying HTML document. This is accomplished with the HTML element <link>:
<link rel="stylesheet" href="example.css">htmlThe link element contains the mandatory attributes rel and href and can optionally be supplemented with the attributes type and media.
Attributes of the link element |
Description |
|---|---|
rel
|
The rel attribute defines the relationship type of the element. The value stylesheet indicates that a stylesheet should be linked.
|
href
|
The href attribute references the file that is to be linked as a stylesheet.
|
type
|
The optional type attribute describes the media type of the file to be linked—text/css in the case of CSS.
|
media
|
The media attribute allows you to define that the referenced stylesheet should only be used for a specific output medium. This makes it possible to provide different stylesheets for various devices. Possible values include screen or print.
|
CSS colour specifications
As outlined in the introduction, CSS colours can be specified using predefined colour names. In real-world use, however, this method is uncommon. The RGB model is used far more frequently, as it allows for a much wider range of colour variations and more precise control over colour values. These values can be easily identified using a colour picker, which Google offers directly as a Quick Answer.

Colour components in the RGB model are defined by decimal values between 0 and 255. A value of 0 means that a colour has no component of the respective base colour, while a value of 255 indicates the maximum component.
Since CSS3, RGB values can be expanded by a fourth value, the alpha channel (a). This indicates the opacity of the colour and is given in values from 0 to 1 (e.g., 0.8). RGB colours are defined in CSS as follows:
rgba(RedValue, GreenValue, BlueValue, Opacity)cssFor example, the following RGBA values yield the base colour blue with a transparency of 50 percent.
rgba(0, 0, 255, 0.5)cssYou can also specify RGB values in hexadecimal.
The most important CSS properties
CSS provides a wide range of properties that let you define styling rules for HTML elements. Each property accepts a defined set of values as specified in the standard. To keep things clear, CSS properties are grouped by areas of application. Here, we focus on the most important ones.
Typography
Among the central features of a website is its typography. CSS provides you with various options to format the text elements of an HTML page.
font-family
If a specific font should be applied to the text elements of a website, the CSS property font-family is used. This makes it possible to define a font stack, which is a prioritised list of suitable fonts. Font stacks are structured so that the preferred font is listed first, followed by fallback alternatives.
.content {
font-family: Georgia, Garamond, serif;
}cssThe example shows a styling rule defined in the CSS file. Georgia is set as the preferred font, with Garamond specified as the fallback font. If Georgia is not available on the user’s system, the web browser will display the text in Garamond instead.
As a fallback mechanism, it is recommended to define a generic font family. This serves as a general placeholder for a group of similar typefaces.
font-style
The CSS property font-style controls the style of a text segment and allows you to define how the characters are slanted, such as italic or oblique.
| Values for text slant | Description |
|---|---|
normal
|
normal font style (default setting) |
italic
|
italic font |
oblique
|
slanted font (even if the font has no italic variant) |
The following example shows a styling instruction for the ‘italic’ font style:
.special-content {
font-family: Arial;
font-style: italic;
}cssfont-variant
The CSS property font-variant is used to define font variants.
| Values for font variants | Description |
|---|---|
normal
|
Normal font variant (default setting) |
small-caps
|
Small capitals (uppercase letters at the height of lowercase letters) for lowercase letters |
all-small-caps
|
Small capitals for uppercase and lowercase letters |
The following example sets the font variant small-caps:
.content {
font-family: Arial;
font-variant: small-caps;
}cssfont-size
The CSS property font-size defines the display size of text elements. This can be in absolute values or relative to surrounding elements. The height of the characters, known as the font size, is specified. Web designers have various notations and units available for this purpose.
Absolute units
Absolute units are based on physical length measurements. However, on the screen, browsers convert all these units to pixels, using a resolution of 96 dpi as a basis. Besides px, absolute units play hardly any role in web design. They are useful primarily for print output.
| Unit | CSS notation | Description |
|---|---|---|
| Pixel | px
|
The unit px corresponds to the size of an element in pixels. Pixels are displayed on screens in relation to dot density (e.g., dots per inch, dpi). As a scaling reference: 1 CSS pixel equals 1/96 of an inch. The user can change the mapping of the px unit to device pixels by zooming in the browser. |
| Centimeter | cm
|
Size in centimeters |
| Millimeter | mm
|
Size in millimeters |
| Inch | in
|
Size in inches (1 in = 2.54 cm) |
| Point | pt
|
Size in points (1 pt equals 1/72 of an inch) |
| Pica | pc
|
Size in picas (1 pica equals 12 points) |
In addition, the font size can be defined using absolute keywords:
| Keyword | Description | Example |
|---|---|---|
xx-small
|
tiny | 9 px |
x-small
|
very small | 10 px |
small
|
small | 13 px |
medium
|
medium (browser default font size) | 16 px |
large
|
large | 19 px |
x-large
|
very large | 24 px |
xx-large
|
huge | 32 px |
Relative units
Relative units refer to font size specifications that are determined in relation to a pre-established size. HTML elements inherit their font size from their respective parent element. A reference for a relative font size can also be a technical benchmark such as the display size of a device or a default value in the web browser.
| Unit | CSS notation | Description |
|---|---|---|
| Percentage | %
|
The unit % specifies the font size as a percentage relative to the inherited font size.
|
| em (font height) | em
|
The unit em is also relative to the parent element. Here, 1em equals 100% of the inherited font size. If no font size is defined for the parent element, the device’s default font size is used.
|
| x-height | ex
|
The reference for the unit ex is the height of the lowercase letter x in the chosen font. If an x-height is not defined for a font, 1ex = 0.5em.
|
| Root-em | rem
|
The unit rem refers to the root element of a document (e.g., the HTML element). 1 rem equals 100% of the font size set for the root element.
|
| Viewport width | vw
|
The unit vw is based on the width of the viewport of a display device. It is defined as: 1vw = 1% of the viewport width.
|
| Viewport height | vh
|
The unit vh is based on the height of the viewport of a display device. It is defined as: 1vh = 1% of the viewport height.
|
The font size can also be defined using relative keywords. The default font size of the browser serves as a guideline here.
| Relative | Description |
|---|---|
smaller
|
The current element is displayed smaller than the parent element. |
larger
|
The current element is displayed larger than the parent element. |
To ensure optimal display of font size on different user devices, it is recommended to use relative units such as em or %.
The basic scheme of font size formatting via CSS corresponds to the following code example:
.content {
font-size: 19em;
}cssline-height
The CSS property line-height controls the line spacing of a text paragraph. It supports the same units of measurement as font-size, with percentage values referring to the font size of the respective text. Alternatively, line-height can be defined as a unitless number. Additional valid values include normal (the default setting) and inherit (which takes the value from the parent element).
A line-height of 1.5 corresponds to a line height of 150 percent of the respective font height or 1.5em.
.content {
line-height: 1.5;
}cssfont-weight
The CSS property font-weight defines the thickness of a text element. Designers use this to display text in bold. Values can be specified as absolute or relative to the parent element.
| Absolute values for the font-weight property | Description |
|---|---|
| 1-1000 | numeric values from 1 (extra thin) to 1000 (extra bold) |
normal
|
normal thickness (equivalent to the value 400) |
bold
|
bold (equivalent to the value 700) |
Numeric values are only relevant for web fonts. In most cases, two font weights are sufficient, namely normal and bold.
.content {
font-weight: normal;
}
.content {
font-weight: bold;
}cssRelative values for the CSS property font-weight define the thickness of a text element in relation to the inherited thickness of the parent element.
| Relative values for the font-weight property | Description |
|---|---|
bolder
|
Bolder than in the parent element |
lighter
|
Thinner than in the parent element |
Text formatting
In addition to font styling, CSS provides various properties for text formatting. These allow you to configure text alignment, adjust spacing between characters and words, or add decorations to text elements.
text-align
The CSS property text-align is used for the alignment of text and inline elements—elements that are part of the text flow, such as images or buttons. Common values include:
leftrightcenterjustifyinherit(like parent element).
The following code results in a centred alignment of the sample text:
.content {
text-align: center;
}cssOther values for the text-align property define the text alignment in relation to the direction of a text (direction).
| Values for relative text alignment | Description |
|---|---|
start
|
Text is aligned to the side where it begins. With a left-to-right direction { direction: ltr; }, the value corresponds to left. With a right-to-left direction { direction: rtl; }, the value corresponds to right.
|
end
|
Text is aligned to the side where the text ends. |
The value start is considered the default value.
All common browsers automatically render the last line of justified text as left-aligned. If this behaviour is not desired, it can be controlled separately using the CSS property text-align-last. The available values correspond to those of the text-align property.
hyphens
In addition, CSS provides the option to enable automatic hyphenation using the hyphens property. The stylesheet language supports the following values for hyphens:
Values for hyphens property |
Description |
|---|---|
manual
|
Manual hyphenation. Soft hyphens are taken into account during hyphenation (default value). |
none
|
No hyphenation. Soft hyphens are ignored, and line breaks occur only at spaces. |
auto
|
Automatic hyphenation. Word breaks follow the rules of the language specified by the HTML lang attribute.
|
inherit
|
The setting is inherited from the parent element. |
word-spacing
The CSS property word-spacing controls the spacing between words within a text element. It allows website operators to define word spacing using explicit size values. The same units shown for font-size are supported, with the exception of percentages. Additional valid values include normal (the default setting) and inherit (which takes the value from the parent element).
The following code example defines a word spacing of 2em. This is added to the default word spacing.
.content {
word-spacing: 2em;
}cssletter-spacing
If the goal is to define the letter spacing rather than the word spacing, the CSS property letter-spacing is used. Here, size specifications are available, excluding percentages, along with the values normal and inherit.
The following code example shows a text section where a word is highlighted with an additional letter spacing of 1em.
.special-content {
letter-spacing: 1em;
}csstext-indent
With the CSS property text-indent, you can define indentations that apply only to the first line of a paragraph. Possible values include positive and negative, as well as percentage values in relation to the width of the respective text block.
The following code example defines an indentation of the first line by 5 percent. The class is assigned in the HTML source code through span elements:
.content {
text-indent: 5%;
}cssTo define hanging paragraphs, the property text-indent is set with a negative value.
text-decoration
The CSS property text-decoration allows you to apply decorative effects, such as underlines, to text elements. Possible values include:
Values for text-decoration property |
Description |
|---|---|
none
|
No text decoration |
underline
|
Each line of the highlighted text section is underlined. |
overline
|
A line is displayed above each line of the highlighted text section. |
line-through
|
Each line of the highlighted text section is struck through. |
inherit
|
The text decoration matches the parent element. |
The following code example defines underlines for selected word groups within the text section:
.content-underline {
text-decoration: underline;
}csstext-transform
The text-transform property allows for text transformations via CSS. This enables text segments to be displayed in uppercase or lowercase without modifying the text source. The property allows the following transformations:
| Values for text-transform property | Description |
|---|---|
capitalize
|
The first letter of each word is displayed as a capital letter. |
uppercase
|
The entire text segment is displayed in uppercase letters. |
lowercase
|
The entire text segment is displayed in lowercase letters. |
none
|
No transformation occurs. |
inherit
|
The transformation matches that of the parent element. |
If the initial letters of a section are to be displayed as capital letters regardless of the original text, the following formatting is suitable:
.content {
text-transform: capitalize;
}cssFont and background colours
When selecting font and background colours, web designers usually rely on the colour codes described earlier, either in decimal or hexadecimal notation. Many CSS properties make use of these colour values.
color
The CSS property color is used for formatting the font colour. Common values include RGB values, hexadecimal codes, or HSL values. Additionally, the values transparent and opacity allow elements to be displayed invisibly. The following code example shows colour formatting using a hexadecimal colour code:
.content {
font-family: Arial;
font-size: 5em;
color: #d82451;
}cssbackground-color
The CSS property background-color is used to assign a background colour to an element. It supports the same values as the color property.
The following code example demonstrates how font and background colours can be styled:
.content {
font-family: Arial;
font-size: 5em;
color: #d82451;
background-color: #24d8ab;
}cssThe formatting instructs the web browser to display all text elements of the class content in burgundy red (#d82451) and to use turquoise green (#24d8ab) as the background.
background-image
Instead of a background colour, a graphic can be loaded as a background for an element. Designers use the property background-image, which contains the path to the graphic as a value according to the following syntax:
.content {
background-image:
url (path to the image file);
}cssInstead of background-image or background-color, you can also use the shorthand background.
Additionally, CSS provides the option to define gradients as backgrounds:
| CSS gradients | Description |
|---|---|
linear-gradient()
|
The function creates a linear gradient. |
radial-gradient()
|
The function creates a radial gradient. |
repeating-linear-gradient()
|
The function creates a repeating linear gradient. |
repeating-radial-gradient()
|
The function creates a repeating radial gradient. |
In our CSS introduction, we focus on the linear-gradient() function as an example. To apply a linear gradient to an element, use the linear-gradient() function as the value for the background property. This requires at least two colour specifications as arguments. The format in which the colours are defined is not relevant.
.content {
width: 400px;
height: 400px;
background: linear-gradient( green, yellow );
}cssFramework
CSS also allows you to add borders to HTML elements. This is particularly recommended for block-level elements such as headings, paragraphs, div elements, or HTML tables, which appear within the body element. Without further styling, content blocks like these extend across the entire available width and are arranged one below the other.
Block-level elements are to be distinguished from inline elements like <b>, <i>, <a>, or <span>. Inline elements appear exclusively within block-level elements. The width of an inline element is determined solely by its own content.
To enclose an entire block-level or inline element in a border, use the borders property. Alternatively, you can define the border design for each side of an element individually.
| Properties for borders | Description |
|---|---|
border
|
Defines the border properties for all sides of the element. |
border-top
|
Defines the properties of the top border edge |
border-right
|
Defines the properties of the right border edge. |
border-bottom
|
Defines the properties of the bottom border edge. |
border-left
|
Defines the properties of the left border edge. |
Both the border property and the properties for individual border sides can be further refined. The relevant values are listed after the property and separated by spaces, following the structure below:
.content {
border: style width color;
}
.content {
border: solid 4px #ff0000;
}cssThe border-radius property also makes it possible to round the edges of a border.
Border type
By selecting a border style, you define a decorative border for the corresponding block-level or inline element. Some border styles only take effect when an appropriate border width is specified.
| Possible values for border type | Description |
|---|---|
none
|
no border |
hidden
|
Does not display a border and suppresses it even for adjacent 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 allow for the creation of different 3D effects. |
The following graphic compares the CSS border types:

Specifying the border type is mandatory. If no border type is specified, the border will not be displayed by the web browser, even if values for border width or colour are present.
Border width
The border width defines the thickness of the border.
| Possible values for border width | Description |
|---|---|
| Length specification | The border width is specified using the units described under font-size. The border width cannot be specified in percentage values.
|
thin
|
Displays a thin border. |
medium
|
Displays a border of medium thickness. |
thick
|
Displays a thick border. |
Border colour
The colour settings for the border-color property correspond to those of the color and background-color properties.
| Possible values for border colour | Description |
|---|---|
| Colour specifications | Colour specifications for borders can be done using keywords, HEX values, and RGB or HSL formats. |
transparent
|
Defines the border as invisible. |
The following code example combines the border property with font and background colour formatting. The rule set is defined in the CSS document for the class frame:
.frame {
font-family: Arial;
font-size: 5em;
color: #d82451;
background-color: #24d8ab;
border: 10px ridge #d82451;
}cssborder-radius
The border-radius property allows you to round the corners of a border in a circular or elliptical shape. Any background is clipped along the defined curve, even if the element has no border. Skillfully used, border-radius can also draw simple geometric shapes.
Possible values for the border property are up to four size specifications, each representing a corner of the border. The assignment can be done using one, two, three, or four values.
| Values for the border-radius property | Description |
|---|---|
| One value | The value applies to all four corners. |
| Two values | The first value defines the top left and bottom right corners. The second value defines the top right and bottom left corners. |
| Three values | 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 | Each corner is defined by its own value, following a clockwise order: top left, top right, bottom right, bottom left. |
The individual values for the border radius are listed separated by spaces after the border-radius property. This results in the following pattern for the declaration (the numeric values are examples):
border-radius: 4em 2em 3em 1em;cssThe border-radius property can be defined in the same rule set as the border property or in separate classes.
The following rule set defines a border with a border-radius of 2 em:
.frame {
height: 100px;
width: 600px;
border: solid 10px #d82451;
border-radius: 2em;
}css
Alternatively, different values for each of the four corners can be defined:
.frame {
height: 100px;
width: 600px;
border: solid 10px #d82451;
border-radius: 2em 1em 3em 4em;
}css
In both cases, the corners of the frame are rounded circularly. If elliptical rounding is required, two values must be specified for each corner. As a result, an elliptically rounded frame can be defined using up to eight values.
border-radius: 1em 4em 1em 4em / 4em 1em 4em 1em;cssThe values before the slash (/) define the radius on the horizontal semi-axis of the ellipse, while the values after the slash define the radius on the vertical semi-axis.
.frame {
height: 100px;
width: 600px;
border: solid 10px #d82451;
border-radius: 1em 4em / 4em 1em;
}css
Any background will automatically be trimmed along the curve.
.frame {
height: 100px;
width: 600px;
border: solid 10px #d82451;
border-radius: 2em;
background-color: #24d8ab;
}css
This applies to both background colours and background images, but not to text elements.

Positioning
The CSS property position allows an element to be taken out of the normal document flow and placed freely on the page. Its position is independent of other elements, whether they follow the standard flow or are positioned themselves.
The position property supports several values, which can be further adjusted using the properties left, right, top, and bottom together with their respective measurement values:
| Values of the position property | Description |
|---|---|
absolute
|
Positions the box relative to the nearest element with a position.
|
relative
|
Positions the box relative to its normal position. |
fixed
|
Positions the box relative to the browser window and stays fixed when scrolling. |
static
|
Natural position of the box in the text flow. When position: static is chosen, position specifications are ineffective. The value static is the default value of position.
|
sticky
|
Positions the box like an element with position: relative as long as it is within the viewport. However, if it threatens to disappear from view, it detaches from the element flow and ‘sticks’ during scrolling. The value sticky can be considered a combination of relative and fixed.
|
Absolute positioning
With position: absolute, an element is removed from the normal document flow and positioned according to the values defined by the corresponding properties. The positioning is relative to the nearest ancestor element that also has a position value set. If no such ancestor exists, the root <html> element is used as the reference point. Elements with position: absolute do not influence the layout of other elements and may either overlap them or be overlapped.
The following rule sets define absolute positioning for the CSS boxes .red, .blue, and .green within the parent element .background.
.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;
}cssThe content boxes .red, .blue, and .green were formatted as semi-transparent surfaces measuring 150 px x 150 px. The content box .background, measuring 500 px x 500 px, is surrounded by a grey border.
The design instructions are incorporated into the HTML code via classes.
<div class="background">
<p class="red"> </p>
<p class="blue"> </p>
<p class="green"> </p>
</div>htmlThe browser view shows the different positions of the boxes within the <div> element. Each element is offset by 50 px downward and to the right. The transparent colouring highlights how elements can overlap when absolute positioning is used.

Relative positioning
With relative positioning, the box remains embedded in the natural element flow, but it can be moved relative to itself through positioning specifications. This means each box is aligned with itself. Preceding and following elements in the flow behave as if the box has not been moved.
To align a box based on its position in the element flow, the corresponding rule set is extended with the declaration position: relative as well as the desired positioning specifications.
The following code block demonstrates this using the example of the blue box:
.blue {
height: 150px;
width: 150px;
background-color: rgba(0,0,255,0.5);
position: relative;
left: 50px;
}cssThe styling directive position: relative with the positioning specification left: 50px results in the blue box being shifted 50 pixels to the left in the browser view.

Relative positioning can also be applied to floated elements.
Fixed CSS boxes
The alignment of fixed boxes is abstracted from the element flow, similar to absolute positioning. All positioning specifications are defined in relation to the viewport. A box fixed in this way always appears in the same spot on the screen—even when a user scrolls through the website. This allows navigation elements like menus or stopper buttons (e.g., ‘Back to Top’) to be pinned in the visible area.
The CSS box model
The CSS box model explains how browsers display and position HTML elements as rectangular areas, or ‘boxes’. At its core, every website consists of an interplay of these boxes, with their arrangement defined by the so-called element flow. By default, elements are laid out from left to right and from top to bottom.
CSS distinguishes between two types of boxes:
- Block boxes (
div,p) by default take up the entire width of their parent element and always start on a new line. - Inline boxes (
span,b,i) are displayed in the text flow and adapt to their content.
The element flow of block and inline boxes can be illustrated by the following graphics:

Block boxes structure the layout, while inline boxes are responsible for text and inline elements. Empty containers like <div> are often used solely for grouping and formatting via CSS.
| Box model layers | Description |
|---|---|
| Content box | The area whose size is determined by the amount of text or the dimensions of an image. For block-level elements, height and width can be defined using the height and width properties. This type of formatting is not available for inline elements.
|
| Padding box | The padding box defines the space between the content box and the border box. |
| Border box | The border box defines the element’s border. |
| Margin box | The margin box defines the space between the current element and its parent element or neighbouring elements. The margin property can also have negative values.
|
To format all four edges of a box at the same time, the properties padding, border, and margin are used:
| Padding | Border | Margin | |
|---|---|---|---|
| top | padding-top
|
border-top
|
margin-top
|
| bottom | 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 properties include size specifications and inherit (corresponding to the parent element). Margins can also be defined using the value auto.
The following graphic shows the schematic structure of a CSS box:

The CSS box model in action
The CSS box model can be illustrated by adding its individual layers step by step to a content box. The starting point is a short text section, which in this example is styled using a class selector:
<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>htmlThe following rule set defines dimensions of 150 px by 150 px for the content box. Additional styling specifies black text on a grey background, and the text is aligned using justified formatting:
.content {
height: 150px;
width: 150px;
color: #000000;
text-align: justify;
background-color: #808080;
}cssWhen applied to the text section, these styling rules produce the following display in the web browser:

The text section appears in the top-left corner of its parent element according to the normal element flow. The text and background colour start without any spacing on the left edge of the browser window and fill the entire available area, with the background ending directly at the text content.
This type of layout looks unappealing and makes reading more difficult. The padding property allows web designers to define inner spacing that separates text from surrounding design elements.
.content {
height: 150px;
width: 150px;
color: #000000;
background-color: #808080;
text-align: justify;
padding: 10px;
}cssAdded to the rule set, the declaration padding: 10px; causes the following change in the front-end view:

The web browser adds an inner spacing of 10 px to all four sides of the content box. A border can be added as another design element.
.content {
height: 150px;
width: 150px;
color: #000000;
background-color: #808080;
text-align: justify;
padding: 10px;
border: 5px solid #d82451;
}cssIn the example code, the border property is used to add a burgundy, solid border to the element.

A border is therefore offset from the content by the defined padding value.
According to the natural element flow, a box styled in this way is placed directly in the top-left corner of its parent element without any spacing. The margin property makes it possible to loosen up the layout by adding outer spacing. The corresponding declaration is simply added to the existing rule set:
.content {
height: 150px;
width: 150px;
color: #000000;
background-color: #808080;
text-align: justify;
padding: 10px;
border: 5px solid #d82451;
margin: 40px;
}cssIn the web browser, such an outer spacing of 40 px is implemented as follows:

Alternatively, instead of specifying a measurement, the margin property can be assigned the value auto. In this case, the box is automatically aligned horizontally centred within the parent element. Vertically, auto has no effect.
The space required by a CSS box can be determined by adding together the values of all relevant components of the box.
Box formatting with float
If the box to be formatted is a block box, subsequent boxes automatically move to the next line according to the element flow.
The automatic line break after a block box is not always desired in practice and can be prevented using the float property. This removes block boxes from the normal element flow and places them in a desired position.
Values for the float property |
Description |
|---|---|
none
|
No floating is applied. float: none; is the default value for a CSS box.
|
left
|
The block-level element is positioned at the left inner edge of its parent element. |
right
|
The block-level element is positioned at the right inner edge of its parent element. |
inherit
|
The float value is inherited from the parent element. |
A box that uses the float property is referred to as a float.
When multiple floats are present, they are arranged in the order in which they appear in the HTML source code, either from left to right (float: left) or from right to left (float: right).
The following code example shows a rule set that includes the float property:
.content {
height: 150px;
width: 150px;
color: #000000;
background-color: #808080;
text-align: justify;
padding: 20px;
border: 5px solid #d82451;
margin: 40px;
float: left;
}htmlWhen this is applied to two HTML elements, they are removed from the element flow and aligned to the left in sequence:
<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>html
The large gap is caused by the combined margins of both boxes. Without using floats, the margins of adjacent elements would collapse into a single margin.
Responsive web design with CSS
To design responsive web design with CSS, the stylesheet language offers two modern layout techniques, which are Flexbox and Grid. Both systems dynamically adjust content to different screen sizes. In combination with CSS media queries, layouts can also be specifically adapted to various devices and screen widths.
Flexbox
With CSS Flexbox (Flexible Box Layout), one-dimensional layouts can be created with ease. Flexbox aligns content either horizontally or vertically, making it ideal for navigations, galleries, or modular content areas.
A flex container is defined by the property display: flex;. All direct child elements automatically become flex items, whose positioning, order, and size can be flexibly controlled.
| Property | Description |
|---|---|
flex-direction
|
Determines the main direction of the flex items. The value row is used for horizontal alignment, and the value column for vertical alignment. row-reverse and column-reverse align from right to left, respectively.
|
justify-content
|
Aligns the flex items along the main axis. flex-start aligns at the start, flex-end at the end of the axis, and center centres them. space-between, space-around, and space-evenly specify the spacing of elements (evenly without edge spacing, equal spacing around all elements, evenly between all items).
|
align-items
|
Aligns the flex items along the cross axis. The values flex-start, flex-end, and center function as they do with flex-direction. Additionally, baseline aligns items with the baseline, and stretch achieves a full container alignment.
|
flex-wrap
|
Determines whether the flex items can wrap to a new line. With nowrap (default), all elements remain in a single line. With wrap and wrap-reverse, line breaks occur (possibly in reverse direction).
|
gap
|
Determines the spacing between the flex items. |
A simple example shows the horizontal arrangement of elements with even spacing:
.container {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
gap: 10px;cssThe rules are applied to the following HTML:
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>htmlIn addition, the behaviour of individual flex items can be controlled separately. The flex property defines how much an element is allowed to grow or shrink in relation to the others. For example, a value of 2 means that the element can grow twice as much:
.item1 {flex: 2; }cssGrid layout
With CSS grid, web page content can be arranged in a two-dimensional grid. This layout system provides precise control over rows and columns, making it easy and flexible to create complex designs. To define a grid, assign the property display: grid; to a parent element. All direct child elements of this container automatically become grid items, which can then be customised using various grid properties.
| Property | Description |
|---|---|
grid-template-columns
|
Defines the column structure of the grid. The most important unit is fr; it indicates how many portions of the available space are used. With auto, the division is done automatically.
|
grid-template-rows
|
Defines the row structure of the grid. The values for grid-template-rows are the same as for grid-template-columns.
|
gap
|
Determines the spacing between grid items |
justify-items
|
Sets the horizontal alignment of the grid items. start aligns left, end aligns right, and center centres the alignment. The default value stretch fills the cell.
|
align-items
|
Sets the vertical alignment of the grid items. The alignment uses the same values as justify-items.
|
An example demonstrates the construction of a grid with three equally wide columns and two rows using uniform fr values:
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: auto auto;
gap: 10px;
}cssEach grid item can also be specifically positioned to span multiple columns or rows. The properties grid-column and grid-row are available for this. The start (inclusive) and end line (exclusive) are specified, separated by a slash (/*/). In the following example, the element spans two columns and one row.
.item1 {
grid-column: 1 / 3;
grid-row: 1;
}cssMedia queries
Media queries allow CSS rules to be applied based on device characteristics. This means the layout can look different on smartphones, tablets, and desktop screens without needing multiple HTML files. A media query can specifically activate or override styles once certain conditions are met. The most common use is adapting to different viewport widths, for which the following values are needed:
| Property/Syntax | Description |
|---|---|
@media
|
Initiates a media query. |
screen, print, all
|
Determines for which media type the rules apply. |
min-width
|
Activates CSS rules at a specific minimum width. |
max-width
|
Activates CSS rules up to a specific maximum width. |
An example shows how a media query can be used to change the layout below a certain width:
/ *Standard layout for larger screens* /
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
/ *Adjustment for smaller screens* /
@media (max-width: 768px) {
.container {
grid-template-columns: 1fr;
}
}cssMultiple conditions can also be combined, for example, to change layouts only on tablets in portrait mode:
@media screen and (min-width: 600px) and (max-width: 900px) and (orientation: portrait) {
body {
font-size: 1.1em;
}
}cssCSS variables
CSS variables (also called custom properties) allow you to store values centrally and use them multiple times in the stylesheet. This way, you can change colours, spacing, or font sizes in one place without having to adjust the entire CSS. This makes the code clearer, easier to maintain, and more consistent.
CSS variables are defined using a double hyphen (--) and are accessed with the var() function.
| Syntax | Description |
|---|---|
--variablename
|
Defines a custom variable. |
var(--variablename)
|
Calls the value of a defined variable. |
:root
|
The global scope (equivalent to the topmost HTML element). |
An example shows how variables are defined and used:
:root {
--main-color: #ff4081;
--text-color: #333;
--padding: 10px;
}
button {
background-color: var(--main-color);
color: var(--text-color);
padding: var(--padding);
}cssThe variables --main-color, --text-color, and --padding are defined in :root, which makes them globally available across the entire page. The button references these variables using var(), so its background colour, text colour, and padding are automatically derived from the defined variable values.




