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 ty­po­graphy of your website.

Sep­ar­at­ing content and present­a­tion

In com­bin­a­tion with HTML, CSS is used to separate content from present­a­tion.

Hypertext Markup Language (HTML) is used to enrich text documents with in­form­a­tion that provides semantic structure for in­di­vidu­al text elements. This markup language forms the found­a­tion 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 in­ter­preted, for example as a heading <h1> or a text paragraph <p>.

Ori­gin­ally, HTML also included rudi­ment­ary design in­struc­tions. However, with HTML5, these are con­sidered outdated and should no longer be used. Instead, the stylesheet language CSS (Cascading Style Sheets) is used to handle present­a­tion rules sep­ar­ately.

Website Builder
From idea to website in record time with AI
  • Intuitive website builder with AI as­sist­ance
  • Create cap­tiv­at­ing 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 in­cor­por­ate separate CSS documents to format web pages. The result is a clear source code, where redundant design in­struc­tions are avoided by ref­er­en­cing separate stylesheets. The fewer the re­pe­ti­tions, the leaner the source code.

If design ad­just­ments are needed, they are made in the central CSS files. This elim­in­ates the need to review and update each in­di­vidu­al HTML document sep­ar­ately. As a living standard, CSS is con­tinu­ously developed by the World Wide Web Con­sor­ti­um (W3C).

Basic structure of CSS syntax

The primary task of CSS is to define the design of a website. For this purpose, prop­er­ties with certain values are assigned to the un­der­ly­ing HTML elements using the stylesheet language. The basic structure of a design in­struc­tion follows this pattern:

Selector { Declaration }
css

The selector iden­ti­fies the HTML element to which a design rule applies. The de­clar­a­tion itself is defined by a property–value pair enclosed in curly braces, with each de­clar­a­tion ending in a semicolon.

HTML elements { property: value; }
css

According to this pattern, a text colour like red can be assigned to a headline, for example:

h2 { color: red; }
css

Web designers have the option to assign a single property to the selector or define com­pre­hens­ive rule sets that include detailed design in­struc­tions. For clarity, a writing style has been es­tab­lished where all prop­er­ties of a rule set are written on separate lines:

selector {
property1: value;
property2: value;
property3: value;
}
css

In practice, a set of prop­er­ties might look like this:

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

The selector iden­ti­fies the HTML element to which a design rule applies. The de­clar­a­tion itself is defined by a property–value pair enclosed in curly braces, with each de­clar­a­tion ending in a semicolon:

selector1, selector2 { declaration }
css

CSS 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 cap­it­al­isa­tion is important.

Type of selector CSS notation De­scrip­tion Spe­cificity
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 in­teg­rated 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
Note

When multiple rules apply to the same element, the selector’s spe­cificity de­term­ines which rule takes pre­ced­ence. Each type of selector carries a defined weight that is used to calculate its overall spe­cificity.

Type selector

The use of various CSS selectors can be il­lus­trated with examples. The following code shows the type selector h2 with a de­clar­a­tion:

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

The format­ting applies to all HTML elements of type h2.

Class selector

Al­tern­at­ively, CSS format­ting can be done using a class selector. This allows designers to apply the same styling in­struc­tions to HTML elements, re­gard­less of their specific type.

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

The format­ting applies to all HTML elements that are assigned the .content class. This as­sign­ment is defined in the HTML code as follows:

<p class="special-text">Example text</p>
html
Note

In 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 ap­pro­pri­ate. The following example shows the format­ting of a nav­ig­a­tion area:

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

The format­ting 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>
html

The advantage of ID selectors is that it is im­me­di­ately 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;
}
css

All text elements are displayed by the web browser in the Helvetica font.

How to integrate CSS into HTML

For a browser to apply CSS format­ting, the styling in­struc­tions must be linked to the HTML source code. Users have three options for doing this:

  • Direct in­teg­ra­tion of the CSS de­clar­a­tion in HTML tags
  • The CSS markup in the HTML head
  • The reference to a separate stylesheet

The latter solution is con­sidered best practice. In real-world use, stylesheets are typically created as external text files and then linked to the document.

CSS de­clar­a­tion in HTML tags

If a CSS de­clar­a­tion 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 in­struc­tion applies using the style attribute. This is known as an ‘inline style’.

<h2 style="color: red;">Subheading</h2>
html

The 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 cum­ber­some and leads to un­ne­ces­sary re­pe­ti­tion.

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 in­ef­fi­cient. Instead, it is re­com­men­ded 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>
html

The rule set within the style element is auto­mat­ic­ally applied to all sub­sequent 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 in­struc­tions are defined in a separate stylesheet, it must be included in the un­der­ly­ing HTML document. This is ac­com­plished with the HTML element <link>:

<link rel="stylesheet" href="example.css">
html

The link element contains the mandatory at­trib­utes rel and href and can op­tion­ally be sup­ple­men­ted with the at­trib­utes type and media.

At­trib­utes of the link element De­scrip­tion
rel The rel attribute defines the re­la­tion­ship type of the element. The value stylesheet indicates that a stylesheet should be linked.
href The href attribute ref­er­ences 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 ref­er­enced 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 spe­cific­a­tions

As outlined in the in­tro­duc­tion, CSS colours can be specified using pre­defined colour names. In real-world use, however, this method is uncommon. The RGB model is used far more fre­quently, as it allows for a much wider range of colour vari­ations and more precise control over colour values. These values can be easily iden­ti­fied using a colour picker, which Google offers directly as a Quick Answer.

Image: Colour picker in the Google search engine
A colour picker allows you to prac­tic­ally display colour values.

Colour com­pon­ents 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 re­spect­ive 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)
css

For example, the following RGBA values yield the base colour blue with a trans­par­ency of 50 percent.

rgba(0, 0, 255, 0.5)
css
Note

You can also specify RGB values in hexa­decim­al.

The most important CSS prop­er­ties

CSS provides a wide range of prop­er­ties 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 prop­er­ties are grouped by areas of ap­plic­a­tion. Here, we focus on the most important ones.

Ty­po­graphy

Among the central features of a website is its ty­po­graphy. 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 pri­or­it­ised list of suitable fonts. Font stacks are struc­tured so that the preferred font is listed first, followed by fallback al­tern­at­ives.

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

The 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.

Tip

As a fallback mechanism, it is re­com­men­ded to define a generic font family. This serves as a general place­hold­er 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 char­ac­ters are slanted, such as italic or oblique.

Values for text slant De­scrip­tion
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 in­struc­tion for the ‘italic’ font style:

.special-content {
font-family: Arial;
font-style: italic;
}
css

font-variant

The CSS property font-variant is used to define font variants.

Values for font variants De­scrip­tion
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;
}
css

font-size

The CSS property font-size defines the display size of text elements. This can be in absolute values or relative to sur­round­ing elements. The height of the char­ac­ters, 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 meas­ure­ments. However, on the screen, browsers convert all these units to pixels, using a res­ol­u­tion 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 De­scrip­tion
Pixel px The unit px cor­res­ponds 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.
Cen­ti­meter cm Size in cen­ti­meters
Mil­li­meter mm Size in mil­li­meters
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 De­scrip­tion 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 spe­cific­a­tions that are de­term­ined in relation to a pre-es­tab­lished size. HTML elements inherit their font size from their re­spect­ive 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 De­scrip­tion
Per­cent­age % The unit % specifies the font size as a per­cent­age 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 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 ensure optimal display of font size on different user devices, it is re­com­men­ded to use relative units such as em or %.

The basic scheme of font size format­ting via CSS cor­res­ponds to the following code example:

.content {
font-size: 19em;
}
css

line-height

The CSS property line-height controls the line spacing of a text paragraph. It supports the same units of meas­ure­ment as font-size, with per­cent­age values referring to the font size of the re­spect­ive text. Al­tern­at­ively, line-height can be defined as a unitless number. Ad­di­tion­al valid values include normal (the default setting) and inherit (which takes the value from the parent element).

A line-height of 1.5 cor­res­ponds to a line height of 150 percent of the re­spect­ive font height or 1.5em.

.content {
line-height: 1.5;
}
css

font-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 De­scrip­tion
1-1000 numeric values from 1 (extra thin) to 1000 (extra bold)
normal normal thickness (equi­val­ent to the value 400)
bold bold (equi­val­ent to the value 700)

Numeric values are only relevant for web fonts. In most cases, two font weights are suf­fi­cient, namely normal and bold.

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

Relative 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 De­scrip­tion
bolder Bolder than in the parent element
lighter Thinner than in the parent element

Text format­ting

In addition to font styling, CSS provides various prop­er­ties for text format­ting. These allow you to configure text alignment, adjust spacing between char­ac­ters and words, or add dec­or­a­tions 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:

  • left
  • right
  • center
  • justify
  • inherit (like parent element).

The following code results in a centred alignment of the sample text:

.content {
text-align: center;
}
css

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

Values for relative text alignment De­scrip­tion
start Text is aligned to the side where it begins. With a left-to-right direction { direction: ltr; }, the value cor­res­ponds to left. With a right-to-left direction { direction: rtl; }, the value cor­res­ponds to right.
end Text is aligned to the side where the text ends.

The value start is con­sidered the default value.

All common browsers auto­mat­ic­ally render the last line of justified text as left-aligned. If this behaviour is not desired, it can be con­trolled sep­ar­ately using the CSS property text-align-last. The available values cor­res­pond to those of the text-align property.

hyphens

In addition, CSS provides the option to enable automatic hy­phen­a­tion using the hyphens property. The stylesheet language supports the following values for hyphens:

Values for hyphens property De­scrip­tion
manual Manual hy­phen­a­tion. Soft hyphens are taken into account during hy­phen­a­tion (default value).
none No hy­phen­a­tion. Soft hyphens are ignored, and line breaks occur only at spaces.
auto Automatic hy­phen­a­tion. 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 per­cent­ages. Ad­di­tion­al 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;
}
css

letter-spacing

If the goal is to define the letter spacing rather than the word spacing, the CSS property letter-spacing is used. Here, size spe­cific­a­tions are available, excluding per­cent­ages, along with the values normal and inherit.

The following code example shows a text section where a word is high­lighted with an ad­di­tion­al letter spacing of 1em.

.special-content {
letter-spacing: 1em;
}
css

text-indent

With the CSS property text-indent, you can define in­dent­a­tions that apply only to the first line of a paragraph. Possible values include positive and negative, as well as per­cent­age values in relation to the width of the re­spect­ive text block.

The following code example defines an in­dent­a­tion of the first line by 5 percent. The class is assigned in the HTML source code through span elements:

.content {
text-indent: 5%;
}
css

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

text-decoration

The CSS property text-decoration allows you to apply dec­or­at­ive effects, such as un­der­lines, to text elements. Possible values include:

Values for text-decoration property De­scrip­tion
none No text dec­or­a­tion
underline Each line of the high­lighted text section is un­der­lined.
overline A line is displayed above each line of the high­lighted text section.
line-through Each line of the high­lighted text section is struck through.
inherit The text dec­or­a­tion matches the parent element.

The following code example defines un­der­lines for selected word groups within the text section:

.content-underline {
text-decoration: underline;
}
css

text-transform

The text-transform property allows for text trans­form­a­tions via CSS. This enables text segments to be displayed in uppercase or lowercase without modifying the text source. The property allows the following trans­form­a­tions:

Values for text-transform property De­scrip­tion
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 trans­form­a­tion occurs.
inherit The trans­form­a­tion matches that of the parent element.

If the initial letters of a section are to be displayed as capital letters re­gard­less of the original text, the following format­ting is suitable:

.content {
text-transform: capitalize;
}
css

Font and back­ground colours

When selecting font and back­ground colours, web designers usually rely on the colour codes described earlier, either in decimal or hexa­decim­al notation. Many CSS prop­er­ties make use of these colour values.

color

The CSS property color is used for format­ting the font colour. Common values include RGB values, hexa­decim­al codes, or HSL values. Ad­di­tion­ally, the values transparent and opacity allow elements to be displayed invisibly. The following code example shows colour format­ting using a hexa­decim­al colour code:

.content {
font-family: Arial;
font-size: 5em;
color: #d82451;
}
css

background-color

The CSS property background-color is used to assign a back­ground colour to an element. It supports the same values as the color property.

The following code example demon­strates how font and back­ground colours can be styled:

.content {
font-family: Arial;
font-size: 5em;
color: #d82451;
background-color: #24d8ab;
}
css

The format­ting 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 back­ground.

background-image

Instead of a back­ground colour, a graphic can be loaded as a back­ground 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);
}
css

Instead of background-image or background-color, you can also use the shorthand background.

Ad­di­tion­ally, CSS provides the option to define gradients as back­grounds:

CSS gradients De­scrip­tion
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 in­tro­duc­tion, 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 spe­cific­a­tions as arguments. The format in which the colours are defined is not relevant.

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

Framework

CSS also allows you to add borders to HTML elements. This is par­tic­u­larly re­com­men­ded for block-level elements such as headings, para­graphs, 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 dis­tin­guished from inline elements like <b>, <i>, <a>, or <span>. Inline elements appear ex­clus­ively within block-level elements. The width of an inline element is de­term­ined solely by its own content.

To enclose an entire block-level or inline element in a border, use the borders property. Al­tern­at­ively, you can define the border design for each side of an element in­di­vidu­ally.

Prop­er­ties for borders De­scrip­tion
border Defines the border prop­er­ties for all sides of the element.
border-top Defines the prop­er­ties of the top border edge
border-right Defines the prop­er­ties of the right border edge.
border-bottom Defines the prop­er­ties of the bottom border edge.
border-left Defines the prop­er­ties of the left border edge.

Both the border property and the prop­er­ties for in­di­vidu­al 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;
}
css

The border-radius property also makes it possible to round the edges of a border.

Border type

By selecting a border style, you define a dec­or­at­ive border for the cor­res­pond­ing block-level or inline element. Some border styles only take effect when an ap­pro­pri­ate border width is specified.

Possible values for border type De­scrip­tion
none no border
hidden Does not display a border and sup­presses 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:

Image: CSS border types
There are different CSS border types with various ap­pear­ances.

Spe­cify­ing 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 De­scrip­tion
Length spe­cific­a­tion The border width is specified using the units described under font-size. The border width cannot be specified in per­cent­age 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 cor­res­pond to those of the color and background-color prop­er­ties.

Possible values for border colour De­scrip­tion
Colour spe­cific­a­tions Colour spe­cific­a­tions 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 back­ground colour format­ting. 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;
}
css

border-radius

The border-radius property allows you to round the corners of a border in a circular or el­lipt­ic­al shape. Any back­ground is clipped along the defined curve, even if the element has no border. Skill­fully used, border-radius can also draw simple geometric shapes.

Possible values for the border property are up to four size spe­cific­a­tions, each rep­res­ent­ing a corner of the border. The as­sign­ment can be done using one, two, three, or four values.

Values for the border-radius property De­scrip­tion
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 in­di­vidu­al values for the border radius are listed separated by spaces after the border-radius property. This results in the following pattern for the de­clar­a­tion (the numeric values are examples):

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

The 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
Image: Frame with rounded corners
A value of 2em results in evenly rounded corners.

Al­tern­at­ively, 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
Image: Frame with rounded corners: A different value was defined for each corner
A different value can be set for each corner.

In both cases, the corners of the frame are rounded cir­cu­larly. If el­lipt­ic­al rounding is required, two values must be specified for each corner. As a result, an el­lipt­ic­ally rounded frame can be defined using up to eight values.

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

The values before the slash (/) define the radius on the ho­ri­zont­al 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
Image: Frame with elliptically rounded corners
The corners can also be rounded el­lipt­ic­ally.

Any back­ground will auto­mat­ic­ally be trimmed along the curve.

.frame {
height: 100px;
width: 600px;
border: solid 10px #d82451;
border-radius: 2em;
background-color: #24d8ab;
}
css
Image: Frame with rounded corners and perfectly fitting background
The back­ground auto­mat­ic­ally fits the frame.

This applies to both back­ground colours and back­ground images, but not to text elements.

Image: Text elements do not automatically adjust to rounded frame edges
Text elements must be aligned sep­ar­ately.

Po­s­i­tion­ing

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 in­de­pend­ent of other elements, whether they follow the standard flow or are po­si­tioned them­selves.

The position property supports several values, which can be further adjusted using the prop­er­ties left, right, top, and bottom together with their re­spect­ive meas­ure­ment values:

Values of the position property De­scrip­tion
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 spe­cific­a­tions are in­ef­fect­ive. 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 con­sidered a com­bin­a­tion of relative and fixed.

Absolute po­s­i­tion­ing

With position: absolute, an element is removed from the normal document flow and po­si­tioned according to the values defined by the cor­res­pond­ing prop­er­ties. The po­s­i­tion­ing 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 over­lapped.

The following rule sets define absolute po­s­i­tion­ing 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;
}
css

The content boxes .red, .blue, and .green were formatted as semi-trans­par­ent surfaces measuring 150 px x 150 px. The content box .background, measuring 500 px x 500 px, is sur­roun­ded by a grey border.

The design in­struc­tions are in­cor­por­ated into the HTML code via classes.

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

The 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 trans­par­ent colouring high­lights how elements can overlap when absolute po­s­i­tion­ing is used.

Image: Absolute positioning of CSS boxes
Three trans­par­ent CSS boxes with different absolute positions.

Relative po­s­i­tion­ing

With relative po­s­i­tion­ing, the box remains embedded in the natural element flow, but it can be moved relative to itself through po­s­i­tion­ing spe­cific­a­tions. 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 cor­res­pond­ing rule set is extended with the de­clar­a­tion position: relative as well as the desired po­s­i­tion­ing spe­cific­a­tions.

The following code block demon­strates 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;
}
css

The styling directive position: relative with the po­s­i­tion­ing spe­cific­a­tion left: 50px results in the blue box being shifted 50 pixels to the left in the browser view.

Image: Relative positioning based on natural element flow
The blue box is shifted through relative po­s­i­tion­ing.

Relative po­s­i­tion­ing can also be applied to floated elements.

Fixed CSS boxes

The alignment of fixed boxes is ab­strac­ted from the element flow, similar to absolute po­s­i­tion­ing. All po­s­i­tion­ing spe­cific­a­tions 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 nav­ig­a­tion 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 rect­an­gu­lar areas, or ‘boxes’. At its core, every website consists of an interplay of these boxes, with their ar­range­ment defined by the so-called element flow. By default, elements are laid out from left to right and from top to bottom.

CSS dis­tin­guishes 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 il­lus­trated by the following graphics:

Image: Three block boxes in CSS element flow
CSS element flow: Block boxes are each displayed in a new row.

Block boxes structure the layout, while inline boxes are re­spons­ible for text and inline elements. Empty con­tain­ers like <div> are often used solely for grouping and format­ting via CSS.

Box model layers De­scrip­tion
Content box The area whose size is de­term­ined by the amount of text or the di­men­sions of an image. For block-level elements, height and width can be defined using the height and width prop­er­ties. This type of format­ting 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 neigh­bour­ing elements. The margin property can also have negative values.

To format all four edges of a box at the same time, the prop­er­ties 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 prop­er­ties include size spe­cific­a­tions and inherit (cor­res­pond­ing to the parent element). Margins can also be defined using the value auto.

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

Image: CSS box model
Schematic rep­res­ent­a­tion of the CSS box model.

The CSS box model in action

The CSS box model can be il­lus­trated by adding its in­di­vidu­al 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>
html

The following rule set defines di­men­sions of 150 px by 150 px for the content box. Ad­di­tion­al styling specifies black text on a grey back­ground, and the text is aligned using justified format­ting:

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

When applied to the text section, these styling rules produce the following display in the web browser:

Image: Content box without padding, border, and margin
When a content box is defined without padding, border, and margin, it appears at the top left in the browser window

The text section appears in the top-left corner of its parent element according to the normal element flow. The text and back­ground colour start without any spacing on the left edge of the browser window and fill the entire available area, with the back­ground ending directly at the text content.

This type of layout looks un­ap­peal­ing and makes reading more difficult. The padding property allows web designers to define inner spacing that separates text from sur­round­ing design elements.

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

Added to the rule set, the de­clar­a­tion padding: 10px; causes the following change in the front-end view:

Image: Content box with padding
Padding defines the inner spacing.

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;
}
css

In the example code, the border property is used to add a burgundy, solid border to the element.

Image: Content box with padding and border
The border encloses the content and padding box.

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 cor­res­pond­ing de­clar­a­tion 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;
}
css

In the web browser, such an outer spacing of 40 px is im­ple­men­ted as follows:

Image: Content box with padding, border, and margin
The margin property enforces an outer spacing between the border box and the parent element.

Al­tern­at­ively, instead of spe­cify­ing a meas­ure­ment, the margin property can be assigned the value auto. In this case, the box is auto­mat­ic­ally aligned ho­ri­zont­ally centred within the parent element. Ver­tic­ally, auto has no effect.

Note

The space required by a CSS box can be de­term­ined by adding together the values of all relevant com­pon­ents of the box.

Box format­ting with float

If the box to be formatted is a block box, sub­sequent boxes auto­mat­ic­ally 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 De­scrip­tion
none No floating is applied. float: none; is the default value for a CSS box.
left The block-level element is po­si­tioned at the left inner edge of its parent element.
right The block-level element is po­si­tioned 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;
}
html

When 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
Image: Two block boxes as left-aligned floats
With the `float` property, block boxes can be displayed side by side without a line break.

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.

Re­spons­ive web design with CSS

To design re­spons­ive web design with CSS, the stylesheet language offers two modern layout tech­niques, which are Flexbox and Grid. Both systems dy­nam­ic­ally adjust content to different screen sizes. In com­bin­a­tion with CSS media queries, layouts can also be spe­cific­ally adapted to various devices and screen widths.

Flexbox

With CSS Flexbox (Flexible Box Layout), one-di­men­sion­al layouts can be created with ease. Flexbox aligns content either ho­ri­zont­ally or ver­tic­ally, making it ideal for nav­ig­a­tions, galleries, or modular content areas.

A flex container is defined by the property display: flex;. All direct child elements auto­mat­ic­ally become flex items, whose po­s­i­tion­ing, order, and size can be flexibly con­trolled.

Property De­scrip­tion
flex-direction De­term­ines the main direction of the flex items. The value row is used for ho­ri­zont­al alignment, and the value column for vertical alignment. row-reverse and column-reverse align from right to left, re­spect­ively.
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. Ad­di­tion­ally, baseline aligns items with the baseline, and stretch achieves a full container alignment.
flex-wrap De­term­ines 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 De­term­ines the spacing between the flex items.

A simple example shows the ho­ri­zont­al ar­range­ment of elements with even spacing:

.container {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
gap: 10px;
css

The 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>
html

In addition, the behaviour of in­di­vidu­al flex items can be con­trolled sep­ar­ately. 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; }
css

Grid layout

With CSS grid, web page content can be arranged in a two-di­men­sion­al 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 auto­mat­ic­ally become grid items, which can then be cus­tom­ised using various grid prop­er­ties.

Property De­scrip­tion
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 auto­mat­ic­ally.
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 De­term­ines the spacing between grid items
justify-items Sets the ho­ri­zont­al 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 demon­strates the con­struc­tion 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;
}
css

Each grid item can also be spe­cific­ally po­si­tioned to span multiple columns or rows. The prop­er­ties 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; 
}
css

Media queries

Media queries allow CSS rules to be applied based on device char­ac­ter­ist­ics. This means the layout can look different on smart­phones, tablets, and desktop screens without needing multiple HTML files. A media query can spe­cific­ally activate or override styles once certain con­di­tions are met. The most common use is adapting to different viewport widths, for which the following values are needed:

Property/Syntax De­scrip­tion
@media Initiates a media query.
screen, print, all De­term­ines 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;
}
}
css

Multiple con­di­tions 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;
}
}
css

CSS variables

CSS variables (also called custom prop­er­ties) 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 con­sist­ent.

CSS variables are defined using a double hyphen (--) and are accessed with the var() function.

Syntax De­scrip­tion
--variablename Defines a custom variable.
var(--variablename) Calls the value of a defined variable.
:root The global scope (equi­val­ent 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);
}
css

The variables --main-color, --text-color, and --padding are defined in :root, which makes them globally available across the entire page. The button ref­er­ences these variables using var(), so its back­ground colour, text colour, and padding are auto­mat­ic­ally derived from the defined variable values.

Author

Reviewers

Go to Main Menu