MDN wants to learn about developers like you: https://www.surveygizmo.com/s3/5171903/MDN-Learn-Section-Survey-Recruiter-Pathway

Diese Übersetzung ist unvollständig. Bitte helfen Sie, diesen Artikel aus dem Englischen zu übersetzen.

There are many types of CSS property values to consider, from numerical values to colors to functions that perform a certain action (like embedding a background image, or rotating an element). Some of these rely on particular units for specifying the exact values they are representing — do you want your box to be 30 pixels wide, or 30 centimeters, or 30 em?

In this guide, we look at more common values like length, color, and simple functions, as well as exploring less common units like degrees, and even unitless numerical values.

Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study the previous articles in this module)
Objective: To learn about the most common types of CSS property values and associated units

Es gibt zahlreiche verschiedene Werte in CSS, einige trifft man sehr häufig an, andere hingegen sehr selten. Wir werden hier nicht alle Werttypen betrachten, sondern nur diejenigen, die für Sie am wahrscheinlichsten hilfreich sein werden, wenn Sie weiter auf dem Pfad schreiten, CSS zu meistern. In diesem Artikel wird es um die nachfolgenden CSS-Werttypen gehen:

  • Numerische Werte: Längenwerte zum Festlegen der z.B. Elementbreite, Randstärke oder Schriftgröße, und einheitslose Ganzzahlwerte um z.B. die relative Zeilenbreite oder Anzahl der Wiederholungen von Animationen festzulegen.
  • Prozente: Festlegen von Größe oder Länge — relativ zur z.B. Breite oder Höhe des elterlichen Containers oder zur Standard-Schriftgröße. Diese ermöglichen häufig erst interaktives Design (z.B. "Liquid Layouts", das sich automatisch an verschiedene Bildschirmgrößen anpasst).
  • Farben: Festlegen von Hintergrundfarben, Textfarben etc.
  • Funktionen: Festlegen von z.B. Hintergrundbildern oder Farbverläufen im Hintergrund.

Außerdem werden Sie mit Beispielen solcher Einheiten über das gesamte CSS-Kapitel hinweg und in so ziemlich jeder anderen CSS-Quelle konfrontiert sein! Sie werden also im Nullkommanichts Routine im Umgang damit haben.

Anmerkung: Sie finden einen Überblick über CSS unit and value types wie auch eine ausführliche Abhandlung der CSS-Einheiten in der CSS Reference; die Einheiten sind jeweils die Einträge, die von spitzen Klammern umgeben sind, beispielsweise <color>.

Numerische Werte

Sie werden Zahlen an vielen Stellen in CSS Einheiten antreffen. In diesem Abschnitt werden die geläufigsten Klassen von Zahlenwerten diskutiert.

Length und size

Sie werden Längen- und Größeneinheiten (siehe <length> als Referenz) ständig in Ihrem CSS verwenden, für Layouts, Typographie und vieles mehr. Lassen Sie uns einen Blick auf ein einfaches Beispiel werfen — zunächst die HTML:

<p>Dies ist ein Absatz.</p>
<p>Dies ist ein Absatz.</p>
<p>Dies ist ein Absatz.</p>

Und nun das CSS:

p {
  margin: 5px;
  padding: 10px;
  border: 2px solid black;
  background-color: cyan;
}

p:nth-child(1) {
  width: 150px;
  font-size: 18px;
}

p:nth-child(2) {
  width: 250px;
  font-size: 24px;
}

p:nth-child(3) {
  width: 350px;
  font-size: 30px;
}

Das Ergebnis ist wie folgt:

Mit diesem Code erzielen wir folgendes:

  • Festlegen von margin, padding und border-width jedes Absatzen auf 5 Pixels, 10 Pixels und 2 Pixel. Ein einzelner Wert für den Außenabstand und den Innenabstand bedeutet, das alle vier Seiten denselben Wert haben. Die Randstärke ist als Teil des Wertes für border angeben.
  • Festlegen von width, also der Breite der drei verschiedenen Absätze zu größer werdenden Pixelwerten, das bedeutet, die Boxen werden immer breiter, je weiter man nach unten geht.
  • Festlegen der font-size, also der Schriftgröße der drei Absätze zu größer werdenden Pixelwerten, das bedeutet, der Text wird immer größer, je weiter man nach unten geht. Die font-size meint dabei die Höhe der einzelnen Buchstaben.

Pixel (px) sind sogenannte absolute Einheiten, weil sie immer dieselbe Größe haben, unanhängig von anderen verwandten Einstellungen. Andere absolute Einheiten sind:

  • q, mm, cm, in: Viertelmillimeter, Millimeter, Zentimeter oder Inch
  • pt, pc: Points (1/72 eines Inch) or Picas (12 points)

Außer Pixel werden Sie vermutlich keine dieser Einheiten öfter als gelegentlich benötigen.

Es gibt außerdem relative Einheiten, die relativ zur derzeitigen font-size oder viewport size des Elementes sind:

  • em: 1em is the same as the font-size of the current element. The default base font-size given to web pages by web browsers before CSS styling is applied is 16 pixels, which means the computed value of 1em is 16 pixels for an element by default. But beware — font sizes are inherited by elements from their parents, so if different font sizes have been set on parent elements, the pixel equivalent of an em can start to become complicated. Don't worry too much about this for now — we'll cover inheritance and font-sizing in more detail in later articles and modules. em are the most common relative unit you'll use in web development.
  • ex, ch: Respectively these are the height of a lower case x, and the width of the number 0. These are not as commonly used or well-supported as em.
  • rem: The rem (root em) works in exactly the same way as the em, except that it will always equal the size of the default base font-size; inherited font sizes will have no effect, so this sounds like a much better option than em, although rems don't work in older versions of Internet Explorer (see more about cross-browser support in Debugging CSS).
  • vw, vh: Respectively these are 1/100th of the width of the viewport, and 1/100th of the height of the viewport. Again, these are not as widely supported as em.

Relative Einheiten sind recht nützlich — Sie können damit die Größe von HTML-Elemente relativ zu ihrer Schrift- oder Darstellungsgröße gestalten, sodass das Layout weiter korrekt aussieht, falls beispielsweise der Text der gesamten Webseite von einem Menschen mit einer Seheinschränkung doppelt so groß dargestellt wird.

Einheitslose Werte

Gelegentlich werden Sie über einheitslose numerische Werte in CSS stolpern — dabei handelt es sich nicht immer um einen Fehler. In einigen Kontexten ist dies tatsächlich völlig in Ordnung. Möchten Sie beispielsweise margin oder padding eines Elementes entfernen, können Sie einfach ohne Einheit den Wert 0 verwenden — 0 ist 0, egal, welche Einheiten vorher benutzt wurden!

margin: 0;

Einheitslose Zeilenhöhe

Ein weiteres Beispiel ist line-height, womit die Höhe jeder Textzeile in einem Element festgelegt wird. Sie können Einheiten für eine bestimmte Zeilenhöhe verwenden, aber häufig ist es einfacher, einen einheitslosen Wert zu verwenden, der als Multiplikationsfaktor agiert. Nehmen wir beispielsweise die folgende HTML:

<p>Blue ocean silo royal baby space glocal evergreen relationship housekeeping
native advertising diversify ideation session. Soup-to-nuts herding cats resolutionary
virtuoso granularity catalyst wow factor loop back brainstorm. Core competency 
baked in push back silo irrational exuberance circle back roll-up.</p>

Und das nachfolgende CSS:

p {
  line-height: 1.5;
}

Dies wird in folgendem Output resultieren:

Hier beträgt die font-size 16px; die Zeilenhöhe wird das 1.5-fache davon betragen, also 24px.

Anzahl von Animationen

CSS Animations erlauben Ihnen, HTML-Elemente auf der Seite zu animieren. Sehen Sie sich dazu ein leichtes Beispiel an, das einen Absatz rotieren lässt, wenn der Mauszeiger darüberliegt. Die HTML für dieses Beispiel ist wirklich sehr einfach:

<p>Hello</p>

Die CSS ist ein klein wenig komplexer:

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

p {
  color: red;
  width: 100px;
  font-size: 40px;
  transform-origin: center;
}

p:hover {
  animation-name: rotate;
  animation-duration: 0.6s;
  animation-timing-function: linear;
  animation-iteration-count: 5;
}

Hier können Sie einige der interessanten Einheiten sehen, über die wir in diesem Artikel nicht explizit sprechen(<angle>, also Winkel, <time>, <timing-function>, <string>...), aber die einzige, für die wir uns an dieser Stelle interessieren ist die Zeile animation-iteration-count: 5; — animation-iteration-count kontrolliert, wie oft die Animation angezeigt wird, wenn sie angestoßen wurde (in diesem Fall, wenn der Mauszeiger über dem Absatz ist), und ist eine schlichte, einheitslose ganze Zahl (Integer, im Computer-Jargon).

Das Ergebnis des Codes ist folgendes:

Prozentwerte

Sie können statt bestimmter numerischer Werte häufig ebenso Prozentwerte verwenden, um die von Ihnen gewünschten Festlegungen zu treffen. Díes erlaubt uns beispielsweise, Boxen zu erstellen, deren Breite immer um einen bestimmten Prozentsatz im Verhältnis zur Breite ihres Elterncontainers verschoben wird. Dies ist im Gegensatz zu Boxen, deren Breite auf einen bestimmten Wert (wie px oder em) festgelegt ist, sodass sie unabhängig von ihrem Elterncontainer immer dieselbe Länge haben.

Betrachten wir ein erklärendes Beispiel.

Zunächst, zwei ähnliche Boxen, in HTML ausgezeichnet:

<div>
  <div class="boxes">Fixed width layout with pixels</div>
  <div class="boxes">Liquid layout with percentages</div>
</div>

And now some CSS to style these boxes:

div .boxes {
  margin: 10px;
  font-size: 200%;
  color: white;
  height: 150px;
  border: 2px solid black;
}

.boxes:nth-child(1) {
  background-color: red;
  width: 650px;
}

.boxes:nth-child(2) {
  background-color: blue;
  width: 75%;
}

Dies führt uns zu folgendem Resultat:

Here, we are giving both divs some margin, height, font-size, border and color. Then, we are giving the first div and second div different background-colors so we can easily tell them apart. We are also setting the first div's width to 650px, and the second div's width to 75%. This way, the first div always has the same width, even if the viewport is resized (it will start to disappear off screen when the viewport becomes narrower than the screen), whereas the second div's width keeps changing when the viewport size changes so that it will always remain 75% as wide as its parent. In this case, the div's parent is the <body> element, which by default is 100% of the width of the viewport.

Note: You can see this effect in action by resizing the browser window this article is in; also try doing the same thing on the raw examples found on Github.

We've also set the font-size to a percentage value: 200%. This works a bit differently to how you might expect, but it does make sense — again, this new sizing is relative to the parent's font-size, as it was with em. In this case, the parent font-size is 16px — the page default, so the computed value will be 200% of this, or 32px. This actually works in a very similar fashion to em — 200% is basically the equivalent of 2em.

These two different box layout types are often referred to as liquid layout (shifts as the browser viewport size changes), and fixed width layout (stays the same regardless). Both have different uses, for example:

  • A liquid layout could be used to ensure that a standard document will always fit on the screen and display well across varying mobile device screen sizes.
  • A fixed width layout can be used to keep an online map the same size; the browser viewport could then scroll around the map, only viewing a certain amount of it at any one time. The amount you can see at once depends on how big your viewport is.

You'll learn a lot more about web layouts later on in the course, in the CSS layout and Responsive design modules (TBD).

Active learning: Playing with lengths

For this active learning, there are no right answers. We'd simply like you to have a go at playing with the width and height of the .inner and .outer divs to see what effects the different values have. Try a percentage value for the .inner div, and see how it adjusts as the .outer div's width changes. Try some fixed values as well, such as pixels and em.

If you make a mistake, you can always reset it using the Reset button.

Colors

There are many ways to specify color in CSS, some of which were implemented more recently than others. The same color values can be used everywhere in CSS, whether you are specifying text color, background color, or whatever else.

The standard color system available in modern computers is 24 bit, which allows the display of about 16.7 million distinct colors via a combination of different red, green, and blue channels, with 256 different values per channel (256 x 256 x 256 = 16,777,216).

Let's run through the different available types of color value.

Note: To convert between the different color systems discussed below, you'll need a color converter. There are lots of easy converters findable online, such as HSL to RGB / RGB to HSL / Hex Colour Converter.

Keywords

The simplest, oldest color types in CSS are the color keywords. These are specific strings representing particular color values. For example, the following code:

<p>This paragraph has a red background</p>
p {
  background-color: red;
}

Gives this result:

This is easy to understand, although it only really allows us to specify obvious color primitives. There are around 165 different keywords available for use in modern web browsers — see the full color keyword list.

You'll probably use pure colors like red, black and white regularly in your work, but beyond that you'll want to use another color system.

Hexadecimal values

The next ubiquitous color system is hexadecimal colors, or hex codes. Each hex value consists of a hash/pound symbol (#) followed by six hexadecimal numbers, each of which can take a value between 0 and f (which represents 15) — so 0123456789abcdef. Each pair of values represents one of the channels — red, green and blue — and allows us to specify any of the 256 available values for each (16 x 16 = 256).

So, for example, this code:

<p>This paragraph has a red background</p>
<p>This paragraph has a blue background</p>
<p>This paragraph has a kind of pinky lilac background</p>
/* equivalent to the red keyword */
p:nth-child(1) {
  background-color: #ff0000;
}

/* equivalent to the blue keyword */
p:nth-child(2) {
  background-color: #0000ff;
}

/* has no exact keyword equivalent */
p:nth-child(3) {
  background-color: #e0b0ff;
}

Gives the following result:

These values are a bit more complex and less easy to understand, but they are a lot more versatile than keywords — you can use hex values to represent any color you want to use in your color scheme.

RGB

The third scheme we'll talk about here is RGB. An RGB value is a function — rgb() — which is given three parameters that represent the red, green and blue channel values of the colors, in much the same way as hex values. The difference with RGB is that each channel is represented not by two hex digits, but by a decimal number between 0 and 255.

Let's rewrite our last example to use RGB colors:

<p>This paragraph has a red background</p>
<p>This paragraph has a blue background</p>
<p>This paragraph has a kind of pinky lilac background</p>
/* equivalent to the red keyword */
p:nth-child(1) {
  background-color: rgb(255,0,0);
}

/* equivalent to the blue keyword */
p:nth-child(2) {
  background-color: rgb(0,0,255);
}

/* has no exact keyword equivalent */
p:nth-child(3) {
  background-color: rgb(224,176,255);
}

This gives the following result:

The RGB system is nearly as well supported as hex values — you probably won't come across any browsers that don't support them in your work. The RGB values are arguably a bit more intuitive and easy to understand than hex values too.

Note: Why 0 to 255 and not 1 to 256? Computer systems tend to count from 0, not 1. So to allow 256 possible values, RGB colors take values in the range of 0-255.

HSL

Slightly less well supported than RGB is the HSL model (not on old versions of Internet Explorer), which was implemented after much interest from designers — instead of red, green and blue values, the hsl() function accepts hue, saturation, and lightness values, which are used to distinguish between the 16.7 million colors, but in a different way:

  1. hue: the base shade of the color. This takes a value between 0 and 360, representing the angles in a round color wheel.
  2. saturation: how saturated is the color? This takes a value from 0-100%, where 0 is no color (it will appear as a shade of grey), and 100% is full color saturation
  3. lightness: how light or bright is the color? This takes a value from 0-100%, where 0 is no light (it will appear completely black) and 100% is full light (it will appear completely white)

Note: An HSL cylinder is useful for visualising the way this color model works. See the HSL and HSV article on Wikipedia.

Now, we'll rewrite our example to use HSL colors:

<p>This paragraph has a red background</p>
<p>This paragraph has a blue background</p>
<p>This paragraph has a kind of pinky lilac background</p>
/* equivalent to the red keyword */
p:nth-child(1) {
  background-color: hsl(0,100%,50%);
}

/* equivalent to the blue keyword */
p:nth-child(2) {
  background-color: hsl(240,100%,50%);
}

/* has no exact keyword equivalent */
p:nth-child(3) {
  background-color: hsl(276,100%,85%);
}

Gives the following result:

The HSL color model is intuitive to designers that are used to working with such color models. For example, it is useful for finding a set of shades to go together in a monochrome color scheme:

/* three different shades of red*/
background-color: hsl(0,100%,50%);
background-color: hsl(0,100%,60%);
background-color: hsl(0,100%,70%);

RGBA and HSLA

RGB and HSL both have corresponding modes — RGBA and HSLA — that allow you to set not only what color you want to display, but also what transparency you want that color to have. Their corresponding functions take the same parameters, plus a fourth value in the range 0–1 — which sets the transparency, or alpha channel. 0 is completely transparent, and 1 is completely opaque.

Let's show another quick example — first the HTML:

<p>This paragraph has a transparent red background</p>
<p>This paragraph has a transparent blue background</p>

Now the CSS — here we are moving the first paragraph downwards with some positioning, to show the effect of the paragraphs overlapping (you'll learn more about positioning later on):

p {
  height: 50px;
  width: 350px;
}

/* Transparent red */
p:nth-child(1) {
  background-color: rgba(255,0,0,0.5);
  position: relative;
  top: 30px;
  left: 50px;
}

/* Transparent blue */
p:nth-child(2) {
  background-color: hsla(240,100%,50%,0.5);
}

This is the result:

Transparent colors are very useful for richer visual effects — blending of backgrounds, semi-transparent UI elements, etc.

Note: Positioning in CSS is discussed later in the course.

Opacity

There is another way to specify transparency via CSS — the opacity property. Instead of setting the transparency of a particular color, this sets the transparency of all selected elements and their children. Again, let's study an example so we can see the difference.

<p>This paragraph is using RGBA for transparency</p>
<p>This paragraph is using opacity for transparency</p>

Now the CSS:

/* Red with RGBA */
p:nth-child(1) {
  background-color: rgba(255,0,0,0.5);
}

/* Red with opacity */
p:nth-child(2) {
  background-color: rgb(255,0,0);
  opacity: 0.5;
}

This is the result:

Note the difference — the first box that uses the RGBA color only has a semi-transparent background, whereas everything in the second box is transparent, including the text. You'll want to think carefully about when to use each — for example RGBA is useful when you want to create an overlaid image caption where the image shows through the caption box but the text is still readable. Opacity, on the other hand, is useful when you want to create an animation effect where a whole UI element goes from completely visible to hidden.

Active learning: Playing with colors

This active learning session also has no right answers — we'd just like you to alter the background color values of the three boxes below that are slightly overlaid on top of one another. Try keywords, hex, RGB/RGBA, HSL/HSLA, and the opacity property. See how much fun you can have.

If you make a mistake, you can always reset it using the Reset button.

Functions

In programming, a function is a reusable section of code that can be run multiple times to complete a repetitive task with minimum effort on the part of both the developer and the computer. Functions are usually associated with languages like JavaScript, Python, or C++, but they exist in CSS too, as property values. We've already seen functions in action in the Colors section, with rgb(), hsl(), etc.:

background-color: rgba(255,0,0,0.5);
background-color: hsla(240,100%,50%,0.5);

These functions calculate what color to use.

But you'll see functions in other places too — anytime you see a name with parenthesis after it, containing one or more values separated by commas, you are dealing with a function. For example:

/* calculate the new position of an element after it has been rotated by 45 degress */
transform: rotate(45deg);
/* calculate the new position of an element after it has been moved across 50px and down 60px */
transform: translate(50px, 60px);
/* calculate the computed value of 90% of the current width minus 15px */
width: calc(90% - 15px);
/* fetch an image from the network to be used as a background image */
background-image: url('myimage.png'); 
/* create a gradient and use it as a background image */ 
background-image: linear-gradient(to left, teal, aquamarine);

One of the more common CSS functions is the url() function notation, which returns a file; generally an image as seen above. There are several image functions, including ones to create linear, radial, and conic gradients.

There are many exciting bits of functionality to use within CSS, which you'll learn about in due course! You can continue below, or dig deeper into the various CSS unit and value types.

Summary

We hope you enjoyed learning about CSS values and units. Don't worry if this doesn't all make complete sense right now; you'll get more and more practice with this fundamental part of CSS syntax as you move forward!

In this module

Schlagwörter des Dokuments und Mitwirkende

Mitwirkende an dieser Seite: DiscW0rld
Zuletzt aktualisiert von: DiscW0rld,