This section is all about how boxes are positioned / laid out on the page.
This section is about the positioning of the box and not about the positioning of the content (text, image) inside the box.
There is many way to locate a word at the right side of your screen and obtain the same visual effect. For instance:
CSS is hard.
All boxes are positioned according to a positioning scheme that is controlled by the position property
Position Value | Scheme / model | Description |
---|---|---|
static (default) | normal flow | Element are laid out one after the other. The offset properties (right, left, top, bottom) does not apply. |
relative | relative positioning | Elements are laid out by the normal flow and an offset is applied |
absolute | absolute positioning | Elements are laid out according to a containing box and the offset properties. The box moves while scrolling |
fixed | fixed positioning | Elements are laid out according to the viewport and the offset properties. The box does not move while scrolling |
sticky | sticky | Keep the box in view within its containing block as the user scrolls |
An element is called a positioned element when its position property has a value other than default (ie static, normal flow).
Positioned elements are said to generate positioned boxes, laid out according to:
A context defines the top element until the positioning model will search for the containing box.
The properties that have an effect on the
This positioning schemes apply to all type of box and are not dependent to the display property.
Ie the display property applies after the positioning algorithm as been applied.
Example with a flex box:
.center-horizontally-absolute-flex {
display: flex;
position: absolute;
top:10px;
left: 50%; /* 50% = center */
border: 1px dashed steelblue; /* to see the box */
height: 80px;
}
body {
height: 100px; /* a absolute box does not participate in the height of the body, we need to give some height */
border: 1px dashed red; /* to see the box */
}
.center-vertically-flex {
display:flex; /* to be able to use the below align-self property (it's a flex property)*/
align-self: center; /* center of the containing flex box */
border: 1px solid steelblue; /* to see the box */
}
<div class="center-horizontally-absolute-flex">
<div class="center-vertically-flex">text</div>
</div>
Because positioning is really tricky, you may also want to use a positioning library.