Positionierung (static, relative, absolute, fixed, sticky)
Mit position steuerst du, wie ein Element im Layout platziert wird. Zusammen mit top, right, bottom und left verschiebst du Elemente gezielt – je nach Wert bleiben sie im Fluss oder werden herausgelöst.
position: static
Der Standardwert. Das Element bleibt im normalen Dokumentenfluss – top, right, bottom und left haben keine Wirkung.
CSS position: static
1.box {
2 position: static;
3 top: 20px;
4 left: 20px; /* hat keine Wirkung */
5}Ausgabe
position: relative
Das Element bleibt im Fluss, kann aber mit top, right, bottom und left verschoben werden. Der ursprüngliche Platz bleibt reserviert. Außerdem wird es zum Bezugspunkt für absolut positionierte Kinder.
CSS position: relative
1.box {
2 position: relative;
3 top: 12px;
4 left: 24px;
5}Ausgabe
position: absolute
Das Element wird aus dem Fluss genommen und relativ zum nächsten Vorfahren mit position ungleich static platziert – sonst relativ zum Viewport.
CSS position: absolute
1.container {
2 position: relative;
3}
4
5.badge {
6 position: absolute;
7 top: 8px;
8 right: 8px;
9}Ausgabe
position: fixed
Wie absolute, aber relativ zum Viewport. Das Element bleibt beim Scrollen an derselben Stelle – typisch für fixierte Header oder Buttons.
CSS position: fixed
1.header {
2 position: fixed;
3 top: 0;
4 left: 0;
5 right: 0;
6}Ausgabe
position: sticky
Eine Mischung aus relative und fixed: Das Element verhält sich zunächst normal und „klebt“ erst ab einem Schwellenwert (top, bottom usw.) im sichtbaren Bereich.
CSS position: sticky
1.header {
2 position: sticky;
3 top: 0;
4}Ausgabe
Scrolle nach unten – der Header bleibt oben haften.
Weiterer Inhalt …
Weiterer Inhalt …
Weiterer Inhalt …
Weiterer Inhalt …
Im nächsten Kapitel lernst du: Float und Clear