Flexbox is well-known for solving common layout problems such as sticky footers and equal-height columns. Beyond those capabilities, it also provides a few other useful features that aren't so popular. Let's explore two of them!
Flexbox and z-index
As you probably already know, the z-index
property works only on positioned elements. By default, all elements have position: static
and aren't positioned. An element is "positioned" when its position
property is set to relative
, absolute
, fixed
, or sticky
.
However, an "unpositioned" element, such as a flex item can also receive the z-index
property. The CSS Flexible Box Layout spec says:
Flex items paint exactly the same as inline blocks [CSS21], except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static.
To understand this behavior, consider the following example:
See the Pen Flexbox and z-index by SitePoint (@SitePoint) on CodePen.
Here we define two elements: the .front
element and the .back
element. The .front
element has one child, a box with a number "1". The .front
element itself is absolutely positioned. Specifically, it has position: fixed
and covers the entire viewport.
Our .back
element is a flex container. It contains two child elements — boxes with numbers "2" and "3". Based on what we've discussed above, we can set the z-index
property of its flex items, even if they aren't positioned elements (i.e. they have position: static
).
Notice that when we add z-index: 2
to the flex items by clicking the button in the demo above, they are positioned on top of the .front
element.
Flexbox and Auto Margins
By applying auto margins to flex items, we're able to solve common UI patterns. To begin with, let's assume that we want to build this typical header layout:
To build it, we'll use flexbox. No floats, fixed widths, or anything like that.
Continue reading %Quick Tip: How z-index and Auto Margins Work in Flexbox%
by George Martsoukos via SitePoint
No comments:
Post a Comment