Skip to content

Kapitel 12: Positionierung-Layout

Mit der position-Eigenschaft können Sie Elemente präzise auf der Webseite positionieren. Dies ist ein Kern-Schwierigkeitsbereich, aber sehr mächtig!

12.1 Positionierungs-Eigenschaft (position)

Die position-Eigenschaft bestimmt, wie ein Element positioniert wird.

📝 Syntax

css
selektor {
    position: wert;
}

🔢 Mögliche Werte

WertBeschreibung
staticStandard (normaler Dokumentfluss)
relativeRelativ zur ursprünglichen Position
absoluteRelativ zum nächsten positionierten Elternelement
fixedRelativ zum Browserfenster (bleibt beim Scrollen stehen)
stickyKombination aus relative und fixed

12.2 Relativ-Positionierung (relative)

position: relative; positioniert ein Element relativ zu seiner ursprünglichen Position.

💡 Verhalten

  • ✅ Das Element bleibt im normalen Dokumentfluss (nimmt Platz ein)
  • ✅ Sie können es mit top, right, bottom, left verschieben
  • ✅ Andere Elemente "sehen" immer noch den ursprünglichen Platz des Elements

🎯 Beispiel

css
.box {
    position: relative;
    top: 20px;    /* 20px nach unten verschieben */
    left: 30px;   /* 30px nach rechts verschieben */
    background-color: lightblue;
    padding: 20px;
}

🎨 Visuelle Erklärung

Ursprüngliche Position:    Nach relative-Verschiebung:
┌─────────────────┐      ┌─────────────────┐
│                 │      │                 │
│    ┌───────┐  │      │    ┌───────┐  │
│    │  Box   │  │  →   │    │  Box   │  │ (20px nach unten, 30px nach rechts)
│    └───────┘  │      │    └───────┘  │
│                 │      │                 │
└─────────────────┘      └─────────────────┘

12.3 Absolut-Positionierung (absolute)

position: absolute; positioniert ein Element relativ zum nächsten positionierten Elternelement (das nicht position: static; hat). Wenn kein solches Elternelement existiert, bezieht es sich auf das <html>-Element.

💡 Verhalten

  • ❌ Das Element wird aus dem normalen Dokumentfluss herausgenommen (nimmt keinen Platz mehr ein)
  • ✅ Sie können es mit top, right, bottom, left präzise positionieren
  • ✅ Andere Elemente verhalten sich, als ob das absolut positionierte Element nicht existieren würde

🎯 Beispiel

HTML:

html
<div class="container">
    <div class="box">Absolut positioniert</div>
    <p>Dies ist ein Absatz.</p>
</div>

CSS:

css
.container {
    position: relative; /* WICHTIG: Container wird zum Bezugspunkt! */
    width: 400px;
    height: 300px;
    background-color: #f0f0f0;
    padding: 20px;
}

.box {
    position: absolute;
    top: 50px;     /* 50px vom oberen Rand des Containers */
    right: 20px;    /* 20px vom rechten Rand des Containers */
    background-color: lightblue;
    padding: 15px;
}

💡 Wichtige Regel!

Für position: absolute; muss das Elternelement (oder ein noch höheres Elternelement) position: relative; (oder einen anderen nicht-statischen Wert) haben!

12.4 Fixed-Positionierung (fixed)

position: fixed; positioniert ein Element relativ zum Browserfenster. Es bleibt an derselben Stelle, auch wenn Sie die Seite scrollen!

💡 Verhalten

  • ❌ Das Element wird aus dem normalen Dokumentfluss herausgenommen
  • ✅ Es bleibt immer im sichtbaren Bereich des Browserfensters (unabhängig vom Scrollen)
  • ✅ Perfekt für Navigationsleisten, "Nach oben"-Buttons, etc.

🎯 Beispiel: Fixed Navigationsleiste

HTML:

html
<nav class="fixed-nav">
    <a href="#">Startseite</a>
    <a href="#">Über uns</a>
    <a href="#">Kontakt</a>
</nav>

<main>
    <p>Hier ist viel Inhalt, damit man scrollen kann...</p>
    <!-- Viele Absätze, damit die Seite lang wird -->
</main>

CSS:

css
.fixed-nav {
    position: fixed;
    top: 0;        /* Ganz oben */
    left: 0;       /* Ganz links */
    width: 100%;    /* Volle Breite */
    background-color: #333333;
    padding: 15px;
    z-index: 1000; /* Damit sie über anderen Elementen liegt (siehe 12.6) */
}

.fixed-nav a {
    color: white;
    text-decoration: none;
    margin-right: 20px;
}

main {
    margin-top: 60px; /* Damit der Inhalt nicht hinter der Navigationsleiste verschwindet */
    padding: 20px;
}

🎯 Beispiel: "Nach oben"-Button

HTML:

html
<button class="back-to-top">Nach oben</button>

CSS:

css
.back-to-top {
    position: fixed;
    bottom: 30px;  /* 30px vom unteren Rand */
    right: 30px;   /* 30px vom rechten Rand */
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 50%;
    width: 60px;
    height: 60px;
    font-size: 24px;
    cursor: pointer;
    display: none; /* Standardmäßig versteckt */
}

/* Aufleuchten, wenn man scrollt (benötigt JavaScript) */
.back-to-top.show {
    display: block;
}

12.5 Positionierungs-Offsets: top/right/bottom/left

Nachdem Sie position festgelegt haben, verwenden Sie top, right, bottom, left, um die genaue Position zu steuern.

📝 Syntax

css
selektor {
    position: absolute; /* Oder relative, fixed, sticky */
    top: wert;
    right: wert;
    bottom: wert;
    left: wert;
}

🔢 Mögliche Werte

  • Längenangaben: 10px, 2rem, 5%
  • auto: Standard (der Browser berechnet den Wert)
  • inherit: Übernimmt den Wert vom Elternelement

🎯 Beispiel

css
/* Element 20px vom oberen und linken Rand positionieren */
.box {
    position: absolute;
    top: 20px;
    left: 20px;
}

/* Element unten rechts positionieren */
.box2 {
    position: fixed;
    bottom: 30px;
    right: 30px;
}

12.6 z-index Eigenschaft: Element-Ebenen steuern

Wenn Elemente übereinander liegen, bestimmt z-index, wer oben und wer unten liegt!

📝 Syntax

css
selektor {
    z-index: ganze-zahl;
}

💡 Verhalten

  • Höherer Wert = näher am Benutzer (liegt oben)
  • Niedrigerer Wert = weiter entfernt vom Benutzer (liegt unten)
  • Negativer Wert = liegt hinter anderen Elementen
  • ❌ Funktioniert nur bei positionierten Elementen (position nicht static)

🎯 Beispiel

css
.box1 {
    position: absolute;
    top: 50px;
    left: 50px;
    width: 200px;
    height: 200px;
    background-color: rot;
    z-index: 1; /* Liegt unten */
}

.box2 {
    position: absolute;
    top: 100px;
    left: 100px;
    width: 200px;
    height: 200px;
    background-color: blau;
    z-index: 2; /* Liegt oben (höherer z-index) */
}

💡 Tipps für z-index

  1. Verwenden Sie grosszügige Zahlen: 10, 100, 1000 (lassen Platz für spätere Anpassungen)
  2. Vermeiden Sie zu hohe Werte: 99999 ist unschön
  3. Planen Sie Ebenen: Header = 1000, Modals = 2000, etc.

12.7 Anfänger-Tipps: Das Elternelement von absolute muss positioniert sein!

Dies ist der häufigste Fehler bei position: absolute;!

❌ Fehler: Elternelement ist nicht positioniert

HTML:

html
<div class="container"> <!-- Kein position-Wert! -->
    <div class="box">Ich bin absolut positioniert</div>
</div>

CSS:

css
.container {
    /* Kein position-Wert (also static) */
    width: 400px;
    height: 300px;
    background-color: #f0f0f0;
}

.box {
    position: absolute;
    top: 50px;
    left: 50px;
    background-color: lightblue;
    padding: 15px;
}

Ergebnis: .box wird relativ zum <html>-Element (ganze Seite) positioniert, nicht zum .container!

✅ Lösung: Elternelement positionieren

CSS (korrigiert):

css
.container {
    position: relative; /* WICHTIG: Macht den Container zum Bezugspunkt! */
    width: 400px;
    height: 300px;
    background-color: #f0f0f0;
}

.box {
    position: absolute;
    top: 50px;
    left: 50px;
    background-color: lightblue;
    padding: 15px;
}

Ergebnis: .box wird jetzt relativ zum .container positioniert!

12.8 Praxis: Fixed Navigationsleiste, "Nach oben"-Button, Popup

Lassen Sie uns das Gelernte in praktischen Beispielen anwenden!

🎯 Beispiel 1: Fixed Navigationsleiste

HTML (index.html):

html
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fixed Navigationsleiste</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <nav class="fixed-nav">
        <a href="#">Startseite</a>
        <a href="#">Über uns</a>
        <a href="#">Dienstleistungen</a>
        <a href="#">Kontakt</a>
    </nav>
    
    <main>
        <h1>Willkommen auf meiner Webseite</h1>
        <p>Hier ist viel Inhalt, damit man scrollen kann...</p>
        <!-- Viele Absätze, damit die Seite lang wird -->
        <p>Lorem ipsum dolor sit amet...</p>
        <p>Lorem ipsum dolor sit amet...</p>
        <p>Lorem ipsum dolor sit amet...</p>
        <p>Lorem ipsum dolor sit amet...</p>
        <p>Lorem ipsum dolor sit amet...</p>
    </main>
</body>
</html>

CSS (style.css):

css
/* Reset */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
}

/* Fixed Navigationsleiste */
.fixed-nav {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background-color: #333333;
    padding: 15px 20px;
    z-index: 1000; /* Liegt über allem anderen */
}

.fixed-nav a {
    color: white;
    text-decoration: none;
    margin-right: 20px;
    font-weight: bold;
}

.fixed-nav a:hover {
    text-decoration: underline;
}

/* Hauptinhalt */
main {
    margin-top: 60px; /* Damit der Inhalt nicht hinter der Navigationsleiste verschwindet */
    padding: 20px;
    max-width: 1200px;
    margin-left: auto;
    margin-right: auto;
}

main h1 {
    margin-bottom: 20px;
}

main p {
    margin-bottom: 15px;
    line-height: 1.6;
}

🎯 Beispiel 2: "Nach oben"-Button

HTML (index.html):

html
<!-- Innerhalb von <body> -->
<button class="back-to-top" id="backToTop">↑</button>

CSS (style.css):

css
/* "Nach oben"-Button */
.back-to-top {
    position: fixed;
    bottom: 30px;
    right: 30px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 50%;
    width: 60px;
    height: 60px;
    font-size: 24px;
    cursor: pointer;
    display: none; /* Standardmäßig versteckt */
    z-index: 1000;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    transition: background-color 0.3s ease;
}

.back-to-top:hover {
    background-color: #45a049;
}

/* Klasse, um den Button anzuzeigen (mit JavaScript hinzufügen) */
.back-to-top.show {
    display: block;
}

JavaScript (script.js) (Zusatz, da Positionierung allein nicht ausreicht):

javascript
// Wenn man scrollt, Button ein- oder ausblenden
window.onscroll = function() {
    var button = document.getElementById("backToTop");
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
        button.classList.add("show");
    } else {
        button.classList.remove("show");
    }
};

// Wenn man auf den Button klickt, nach oben scrollen
document.getElementById("backToTop").onclick = function() {
    document.body.scrollTop = 0; // Für Safari
    document.documentElement.scrollTop = 0; // Für Chrome, Firefox, IE und Opera
};

🎯 Beispiel 3: Popup (Modal)

HTML (index.html):

html
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Popup Beispiel</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <button class="open-modal-btn">Popup öffnen</button>
    
    <!-- Popup-Hintergrund (Overlay) -->
    <div class="modal-overlay" id="modalOverlay">
        <!-- Popup-Inhalt -->
        <div class="modal-content">
            <h2>Willkommen!</h2>
            <p>Dies ist ein Popup-Fenster.</p>
            <button class="close-modal-btn" id="closeModalBtn">Schließen</button>
        </div>
    </div>
    
    <script src="script.js"></script>
</body>
</html>

CSS (style.css):

css
/* Reset */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
    padding: 50px;
    text-align: center;
}

/* Button zum Öffnen des Popups */
.open-modal-btn {
    padding: 15px 30px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 18px;
}

/* Popup-Hintergrund (Overlay) */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5); /* Halb-transparenter Hintergrund */
    display: none; /* Standardmäßig versteckt */
    justify-content: center;
    align-items: center;
    z-index: 2000; /* Liegt über der Navigationsleiste */
}

/* Popup-Inhalt */
.modal-content {
    background-color: white;
    padding: 40px;
    border-radius: 12px;
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
    max-width: 500px;
    width: 90%;
    text-align: center;
}

.modal-content h2 {
    margin-bottom: 20px;
    color: #333333;
}

.modal-content p {
    margin-bottom: 30px;
    color: #666666;
    line-height: 1.6;
}

.close-modal-btn {
    padding: 10px 20px;
    background-color: #f44336;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

/* Klasse, um das Popup anzuzeigen (mit JavaScript hinzufügen) */
.modal-overlay.show {
    display: flex;
}

JavaScript (script.js) (Zusatz):

javascript
// Popup öffnen
document.querySelector('.open-modal-btn').onclick = function() {
    document.getElementById('modalOverlay').classList.add('show');
};

// Popup schließen
document.getElementById('closeModalBtn').onclick = function() {
    document.getElementById('modalOverlay').classList.remove('show');
};

// Popup schließen, wenn man auf den Hintergrund klickt
document.getElementById('modalOverlay').onclick = function(e) {
    if (e.target === this) {
        this.classList.remove('show');
    }
};

📝 Zusammenfassung

In diesem Kapitel haben Sie gelernt:

  • ✅ Die position-Eigenschaft (static, relative, absolute, fixed, sticky)
  • position: relative; (relativ zur ursprünglichen Position)
  • position: absolute; (relativ zum nächsten positionierten Elternelement)
  • position: fixed; (relativ zum Browserfenster)
  • ✅ Positions-Offsets (top, right, bottom, left)
  • z-index (Element-Ebenen steuern)
  • ✅ Dass das Elternelement von absolute positioniert sein muss!
  • ✅ Praktische Beispiele: Fixed Navigationsleiste, "Nach oben"-Button, Popup

🎯 Nächste Schritte

Im nächsten Kapitel werden wir:

  1. Flexbox-Layout erlernen (modernes Layout, einfach und effizient)
  2. Container- und Item-Eigenschaften üben
  3. Praktische Projekte zur Navigation und Kartenlayouts erstellen

Bereit für mehr? Los geht's! 🎨

Frei für alle Anfänger