CSS ::before und ::after content | mediaevent.de (2024)

Content – Inhalt – mit CSS erzeugen

::before und ::after sind Pseudo-Elemente. Sie sprechen keine HTML-Elemente an und erzeugen bei der Anzeige der Seite Inhalt, den es im HTML-Markup nicht gibt.

Darum Achtung: Der Inhalt, der durch CSS content erzeugt wird, wird zwar vom Browser gerendert, taucht nicht im Dokument auf und ändert das HTML-Dokument nicht.

Die generelle Syntax für die Pseudo-Elemente before und after für das Einsetzen von Inhalt ist

 Zeichenkette ───┐ ┌── ein Attribut des Selektors │ │ ▼ ▼selector::before { content: "string" attr(x) attr(y) "string"; }selector::after { content: url(…) attr(x) attr(y) "string"; } ▲ └--- url (z.B. ein Adresse eines Bildes)

Einfaches Beispiel

Bambus-Stricknadeln 4 bis 6 nur € 4,95

.offer::before { content: url(needles.svg) "***"; color: var(--accent); font-size:2rem;}<p class="offer">Bambus-Stricknadeln 4 bis 6 nur € 4,95</p>

::before und ::after erzeugen Inhalt vor oder nach den Inhalt eines Elements. Auf Elemente ohne Inhalt haben (z.B. <input …>, <img …>, <iframe …>) haben sie keinen Einfluß.

content mit attr()

Neben dem einfachen Einfügen eines Textes durch content: "string" kann die content-Eigenschaft durch Attribute erweitert werden. Ein Attribut ist z.B. die URL eines Bildes.

Caramels muffin topping.
Bear claw marshmallow chocolate bar pudding muffin jelly beans pie. Cookie croissant pastry chocolate cake tootsie roll.

Blindtext von Cupcake Ipsum

.cupcake::before { string attr string | | | content: "Rezept " url("cupcake.svg") " neu! "; line-height: 1em; color: firebrick; margin-right: 1em;}<a href="rezept.html" class="cupcake">Caramels muffin topping</a>

Wenn ein Bild mit ::before vor dem Text bzw. ::after nach dem Text eingesetzt wird, benutzt die content-Eigenschaft die URL des Bildes. Keine Anführungszeichen rund um url(), denn so würde url() als Text und nicht als Source-URL des Bildes dargestellt. Bei einem Bild braucht der URL-String – der Pfad zum Bild im src-Attribut – Anführungszeichen. Ein einfacher Text hingegen sitzt direkt in Anführungszeichen.

Und noch ein Beispiel: title-Attribut eines abbr-Tags im Druck und auf Touchscreens anzeigen:

Radar

abbr[title]:after {content: " (" attr(title) ") "}/* Auf Notebook und Desktop-Monitoren nur kennzeichnen */@media (min-width:1160px) { abbr[title] {border-bottom: 1px dotted gray} abbr[title]:after {content: "" }}

Neben der content-Eigenschaft können weitere Eigenschaften (z.B. color, font-size, …) wie gewohnt in die Regel eingefügt werden.

URL eines Links beim Druck ausgeben

Die CSS-Eigenschaft content setzt im folgenden Beispiel ein Bild vor einen Link und hinter den Link die ausgeschriebene Adresse in runde Klammern. Interessant ist eine derartige Eigenschaft z.B. für das Print-Stylesheet einer Webseite, wobei der Benutzer mit dem Text innerhalb des a-Tags nichts anfangen kann.

Als Attribut kann dann das href-Attribut des a-Tags eingesetzt werden.

a.show::before { content: url(bild.png) " " attr(href) " ";}a.show::after { content: " (https://www.mediaevent.de" attr(href) ") ";}…<p><a class="show" href="/css/generated.html">Hier ist ein Link</a></p>

Hier ist ein Link

Mit dem href-Attribut eines a-Elements funktionieren ::before und ::after prima. Was nicht geht: before / after wirkt nicht bei img-Elementen, denn ein img-Tag hat keinen Inhalt.

Einfacher oder doppelter Doppelpunkt

Pseudo-Klassen wie :hover oder :target entstehen z.B. bei Benutzeraktionen oder durch eine bestimmte Position im HTML wie :first-child oder :last-child. Ihr Kennzeichen ist ein einfacher Doppelpunkt. Pseudo-Elemente sind Elemente, die es so im HTML nicht gibt: ::before, ::after, ::first-letter, ::last-line.

Pseudo-Klassen und Pseudo-Elemente lassen sich miteinander kombinieren, z.B. um einen Link beim Hovern mit der Maus herauszustellen.
 ┌ Pseudo-Klasse │ ▼ a:hover::before { ▲ │ └── Pseudo-Element………}ul:last-child::after {………}

Mit alten Versionen von CSS gab es nur den einfachen Doppelpunkt. Da die modernen Browser den einfachen Doppelpunkt noch unterstützen, gibt es keinen Unterschied zwischen :before und ::before oder :after und ::after.

Listenkugeln mit CSS::before und content: ersetzen

  • HTML
  • Javascript

Was durch die Eigenschaft content: vor oder nach einem Selektor gesetzt wird, kann durch weitere CSS-Eigenschaften gestylt werden.

.listbef li::before { content: " ♥ "; color: firebrick; font-size: 2em; }

In den content-String müssen Sonderzeichen entweder direkt oder in hexadezimaler Schreibweise eingegeben werden. Als HTML-Entity-Name oder in der üblichen dezimalen Kodierung würde die Zeichenfolge einfach wörtlich ausgegeben.

.with-hearts::before { content: "&hearts"; color:red; }.with-hex::before { content: "&#9829;"; color:red; }
  • HTML-Entity-Name &hearts;
  • HTML-Entity in hexadezimaler Schreibweise &#9829;

HTML-Sonderzeichen – Schreibweisen mit Dezimal-zu-Hex-Rechner.

Nummerieren mit Zählern (counter)

Während HTML uns bereits die Erzeugung der Listenpunkte und die Nummerierung von Aufzählungen abnimmt (mit dem <ul>- und <ol>-Tag), ermöglichen before und after auch die automatische Erzeugung von Zählern (CSS Counter) in verschachtelten Listen und von Tabellenzeilen.

Anders als ungeordnete Listen mit HTML ol können CSS counter Elemente zählen und nummerieren, die Markup nicht direkt aufeinander folgen.

CSS content

Erblich: Nein

content
wird zusammen mit den Pseudoelementen ::before und ::after benutzt, um Inhalt entweder vor oder hinter dem gebenen CSS-Selektor einzufügen. Der eingefügte Inhalt kann aus Zeichenketten, Anführungszeichen, URLs oder Zählern bestehen.
Werte
[ <string> | <uri> | <counter> | attr(X) | open-quote | close-quote | no-open-quote | no-close-quote ]+ | inherit

CSS content wird nicht vererbt. Da aber ::before und ::after ihre Eigenschaften vererben, können verschiedene CSS-Eigenschaften auf den Inhalt angewendet werden.

none
verhindert die Generierung des Pseudoelements
normal
wirkt wie none
<counter>
(name, string, list-style-type) fügt alle Zähler mit Namen als Inhalt ein und stellt sie in dem angegebenen Listenstil dar (z.B. decimal 1,2,3 ..., upper-latin I, II, III …).
close-quote
close-quote fügt ein schließendes Hochkomma ein, wie es in der CSS-Eigenschaft für verschachtelte Hochkommas definiert ist.
no-close-quote
fügt kein schließendes Hochkomma ein, sondern zählt die CSS-Eigenschaft quotes herunter.
no-open-quote
fügt kein öffnendes Hochkomma ein, sondern zählt die CSS-Eigenschaft quotes hoch.
open-quote
fügt ein öffnendes Hochkomma ein, wie es in der CSS-Eigenschaft für verschachtelte Hochkommas definiert ist.
string
fügt eine Zeichenkette oder einen Text in Hochkommas ein.
<uri>
ist eine externe Resource – z.B. die Adresse eines Bildes.
CSS ::before und ::after content | mediaevent.de (2024)

FAQs

What is *:: before and *:: after in CSS? ›

Definition and Usage

The ::before selector inserts something before the content of each selected element(s). Use the content property to specify the content to insert. Use the ::after selector to insert something after the content.

What does :: before and :: after mean? ›

:before and :after are there to allow you to add content either before or after an element from within the CSS.

Why is :: after not working? ›

If the content property is not specified, has an invalid value, or has normal or none as a value, then the ::after pseudo-element is not rendered. It behaves as if display: none is set. Note: CSS introduced the ::after notation (with two colons) to distinguish pseudo-classes from pseudo-elements.

How to add content using after in CSS? ›

The CSS ::after selector can be used to insert content after the content of the selected element or elements. It's used by attaching ::after to the element it is to be used on. In the example above, we're appending " - Buzz Lightyear" in blue to the element with the class buzz .

When should I use before and after CSS? ›

CSS ::before and ::after pseudo-elements allow you to insert “content” before and after any non-replaced element (e.g. they work on a <div> but not an <input> ). This effectively allows you to show something on a web page that might not be present in the HTML content.

When to use :: before? ›

::before. In CSS, ::before creates a pseudo-element that is the first child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.

What does :: after mean? ›

After means 'later than' and 'next in time or place'. … After as a preposition and conjunction. After means 'later than' and 'next in time or place'. … After or afterwards as an adverb. We can use after as an adverb, but afterwards is more common.

What is an example of post meaning after? ›

The English prefix post- means “after.” Examples using this prefix include postgame and postseason. An easy way to remember that the prefix post- means “after” is through the word postpone, for when you postpone something, you put it on your agenda to do “after” the current time.

What is the use of :: in CSS? ›

For example, ::first-line can be used to change the font of the first line of a paragraph. Double colons ( :: ) are used for pseudo-elements. This distinguishes pseudo-elements from pseudo-classes that use single colon ( : ) in their notation. You can use only one pseudo-element in a selector.

Why before and after not working in CSS? ›

If you want :before and :after to work, you need to give them content , otherwise they don't really 'exist'. The easiest thing to do is, in the css, set content: '' for both pseudoelements. Also, you need to make sure position: relative is set to the element.

How to put an image in content in CSS? ›

To add images to a page, we use the <img> inline element. The <img> element is a self-containing, or empty, element, which means that it doesn't wrap any other content and it exists as a single tag. For the <img> element to work, a src attribute and value must be included to specify the source of the image.

What is :: before and :: after? ›

In fact, MDN defines ::before as “the first child of the selected element” and ::after as “the last child of the selected element”. Because these pseudo elements appear within the selected element, they can only be used for container tags and not for empty tags.

How do you align after content in CSS? ›

Tip: Use the justify-content property to align the items on the main axis (horizontally). Note: The align-content property can also be used on a grid container to align grid items in the block direction. For pages in English, block direction is downward and inline direction is left to right.

How do I fix content in CSS? ›

To make text fixed, you can use the CSS position property with a value of fixed . This will position the element relative to the viewport, meaning that it will not move even if the user scrolls down the page.

What is the meaning of *:: selection in CSS? ›

Definition and Usage

The ::selection selector matches the portion of an element that is selected by a user.

What does * indicate in CSS? ›

The * in CSS represents the Universal Selector. The asterisk symbol, to put it plainly.

What is the quote before and after in CSS? ›

CSS quotes property is defined to specify the quotation marks used for more nesting levels while they are inserted using the content property. These quotes can be added to any element and seek the benefit of pseudo-elements::before and :: after to insert the quotation marks at the beginning and end of the quote.

What is the correct order of CSS? ›

Order of CSS layouting as defined in the CSS specification: position: absolute may override float: left/right . float: left/right may override display , with the exception of display: none . So the order is: position , float , display .

Top Articles
Latest Posts
Article information

Author: Trent Wehner

Last Updated:

Views: 6646

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Trent Wehner

Birthday: 1993-03-14

Address: 872 Kevin Squares, New Codyville, AK 01785-0416

Phone: +18698800304764

Job: Senior Farming Developer

Hobby: Paintball, Calligraphy, Hunting, Flying disc, Lapidary, Rafting, Inline skating

Introduction: My name is Trent Wehner, I am a talented, brainy, zealous, light, funny, gleaming, attractive person who loves writing and wants to share my knowledge and understanding with you.