CSS Fundamentals: Floating and Positioning
To center a block-level element, use the margin property as follows:
margin: 0 auto;
This automatically calculates equal left and right spacing within the available space.
To align containers with and without text, apply vertical-align: top to the elements. This property is applicable only to inline and inline-block elements.
Floating is a layout technique that removes elements from the standard documant flow. Elements with float will no longer be treated as block or inline elements. For example:
span { width: 200px; height: 200px; background-color: red; float: left; }
.right { float: right; }
Floating can cause issues such as parent elements not expanding to contain their children and overlapping with standard document flow elements. To address these problems, consider the following solutions:
- Set an explicit height on the parent element.
- Use a clear element between the floating and standard document flow elements.
- Apply overflow: hidden to the parent of the floating elements.
- Use pseudo-elements with the clear property.
Positioning allows for precise placement of elements. The main types include:
- Relative positioning (position: relative): The element moves relative to its original position but still occupies space.
- Absolute positioning (position: absolute): The element is positioned relative to the nearest positioned ancestor.
- Fixed positioning (position: fixed): The element is positioned relative to the browser viewport and remains in place during scrolling.
- Sticky positioning (position: sticky): Combines aspects of relative and fixed positioning, allowing an element to stick to a specific position as the user scrolls.
When using any positioning, at least one directional property (top, bottom, left, or right) must be specified.