Positioning Overlay Content with CSS Grid
place-items: center
declared on the container, all of its direct children will overlap one another.The next step is to set alignment values on individual elements. The
Not news to any web developer in 2021: CSS Grid is an incredibly powerful tool for creating complex, distinct two-dimensional modern web layouts.
Recently, I have been experimenting with CSS Grid and alignment properties to create component layouts that contain multiple overlapping elements. These layouts could be styled using absolute positioning and a mix of offset values (top
, right
, bottom
, left
), negative margins, and transforms. But, with CSS Grid, positioning overlay elements can be built using more logical, readable properties and values. The following are a few examples of where these grid properties come in handy.
It will help to read up on grid-template-areas
and grid-area
properties if you’re not yet familiar with them.
Expanding images inside limited dimensions
In the demo, there is a checkbox that toggles the overflow visibility so that we can see where the image dimensions expand beyond the container on larger viewport widths.
Here’s a common hero section with a headline overlapping an image. Although the image is capped with a max-width
, it scales up to be quite tall on desktop. Because of this, the content strategy team has requested that some of the pertinent page content below the hero remain visible in the viewport as much as possible. Combining this layout technique and a fluid container max-height
using the CSS clamp()
function, we can develop something that adjusts based on the available viewport space while anchoring the hero image to the center of the container.
CSS clamp()
, along with the min()
and max()
comparison functions, are well-supported in all modern browsers. Haven’t used them? Ahmad Shadeed conducts a fantastic deep dive in this article.
Open this Pen and resize the viewport width. Based on the image dimensions, the container height expands until it hits a maximum height. Notice that the image continues to grow while remaining centered in the container. Resize the viewport height and the container will flex between its max-height
’s lower and upper bound values defined in the clamp()
function.
Prior to using grid for the layout styles, I might have tried absolute positioning on the image and title, used an aspect ratio padding trick to create a responsive height, and object-fit
to retain the ratio of the image. Something like this could get it there:
.container {
position: relative;
max-height: clamp(400px, 50vh, 600px);
}
.container::before {
content: '';
display: block;
padding-top: 52.25%;
}
.container > * {
max-width: 1000px;
}
.container .image {
position: absolute;
top: 0;
left: 50%;
transform: translateX(-50%);
width: 100%;
height: 100%;
object-fit: cover;
}
.container .title {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100%;
text-align: center;
}
Maybe it’s possible to whittle the code down some more, but there’s still a good chunk of styling needed. Managing the same responsive layout with CSS Grid will simplify these layout style rules while making the code more readable. Check it out in the following iteration:
.container {
display: grid;
grid-template: "container";
place-items: center;
place-content: center;
overflow: hidden;
max-height: clamp(450px, 50vh, 600px);
}
.container > * {
grid-area: container;
max-width: 1000px;
}
place-content: center
instructs the image to continue growing out from the middle of the container. Remove this line and see that, while the image is still vertically centered via place-items
, once the max-height
is reached, the image will stick to the top of the container block and go on scaling beyond its bottom. Set place-content: end center
and you’ll see the image spill over the top of the container.
This behavior may seem conceptually similar to applying object-fit: cover
on an image as a styling method for preserving its intrinsic ratio while resizing to fill its content-box dimensions (it was utilized in the absolute position iteration). However, in this grid context, the image element governs the height of its parent and, once the parent’s max-height
is reached, the image continues to expand, maintaining its ratio, and remains completely visible if the parent overflow is shown. object-fit
could even be used with the aspect-ratio
property here to create a consistent aspect ratio pattern for the hero image:
.container .image {
width: 100%;
height: auto;
object-fit: cover;
aspect-ratio: 16 / 9;
}
The overlay grid-area
Moving on to the container’s direct children, grid-area
arranges each of them so that they overlap the same space. In this example, grid-template-areas
with the named grid area makes the code a little more readable and works well as a pattern for other overlay-style layouts within a component library. That being said, it is possible to get this same result by removing the template rule and, instead of grid-area: container
, using integers:
.container > * {
grid-area: 1 / 1;
}
This is shorthand for grid-row-start
, grid-column-start
, grid-row-end
, and grid-column-end
. Since the siblings in this demo all share the same single row/column area, only the start lines need to be set for the desired result.
Setting place-self
to place itself
Another common overlay pattern can be seen on image carousels. Interactive elements are often placed on top of the carousel viewport. I’ve extended the first demo and replaced the static hero image with a carousel.
Same story as before: This layout could fall back on absolute positioning and use integer values in a handful of properties to push and pull elements around their parent container. Instead, we’ll reuse the grid layout rulesets from the previous demo. Once applied, it appears as you might expect: all of the child elements are centered inside the container, overlapping one another.
The next step is to set alignment values on individual elements. The place-self
property—shorthand for align-self
and justify-self
—provides granular control over the position of a single item inside the container. Here are the layout styles altogether:
.container {
display: grid;
grid-template:"container";
place-items: center;
place-content: center;
overflow: hidden;
max-height: clamp(450px, 50vh, 600px);
}
.container > * {
grid-area: container;
max-width: 1000px;
}
.title {
place-self: start center;
}
.carousel-control.prev {
place-self: center left;
}
.carousel-control.next {
place-self: center right;
}
.carousel-dots {
place-self: end center;
}
There’s just one small problem: The title and carousel dot indicators get pulled out into the overflow when the image exceeds the container dimensions.
To properly contain these elements within the parent, a grid-template-row
value needs to be 100% of the container, set here as one fractional unit.
.container {
grid-template-areas: "container";
grid-template-rows: 1fr;
}
For this demo, I leaned into the the grid-template
shorthand (which we will see again later in this article).
.container {
grid-template: "container" 1fr;
}
After providing that little update, the overlay elements stay within the parent container, even when the carousel images spread beyond the carousel’s borders.
Alignment and named grid-template-areas
Let’s use the previous overlay layout methods for one more example. In this demo, each box contains elements positioned in different areas on top of an image.
For the first iteration, a named template area is declared to overlay the children on the parent element space, similar to the previous demos:
.box {
display: grid;
grid-template-areas: "box";
}
.box > *,
.box::before {
grid-area: box;
}
The image and semi-transparent overlay now cover the box area, but these style rules also stretch the other items over the entire space. This seems like the right time for place-self
to pepper these elements with some alignment magic!
.tag {
place-self: start;
}
.title {
place-self: center;
}
.tagline {
place-self: end start;
}
.actions {
place-self: end;
}
That‘s looking great! Every element is positioned in their defined places over the image as intended. Well, almost. There’s a bit of nuance to the bottom area where the tagline and action buttons reside. Hover over an image to reveal the tagline. This might look fine with a short string of text on a desktop screen, but if the tagline becomes longer (or the boxes in the viewport smaller), it will eventually extend behind the action buttons.
To clean this up, the grid-template-areas
use named areas for the tagline and actions. The grid-template-columns
rule is introduced so that the actions container only scales to accommodate the size of its buttons while the tagline fills in the rest of the inline area using the 1fr
value.
.box {
display: grid;
grid-template-areas: "tagline actions";
grid-template-columns: 1fr auto;
}
This can also be combined with the grid-template
shorthand. The column values are defined after a slash, like so:
.box {
grid-template: "tagline actions" / 1fr auto;
}
The grid-area
is then converted to integers now that the “box” keyword has been removed.
.box > *,
.box::before {
grid-area: 1 / 1 / -1 / -1;
}
Everything should look the way it did before. Now for the finishing touch. The tagline
and actions
keywords are set as their respective element grid-area
values:
.tagline {
grid-area: tagline;
place-self: end start;
}
.actions {
grid-area: actions;
place-self: end;
}
Now, when hovering over the cards in the demo, the tagline wraps to multiple lines when the text becomes too long, rather than pushing past the action buttons like it did before.
Named grid lines
Looking back at the first iteration of this code, I really liked having the default grid-area
set to the box
keyword. There’s a way to get that back.
I’m going add some named grid lines to the template. In the grid-template
rule below, the first line defines the named template areas, which also represents the row. After the slash are the explicit column sizes (moved to a new line for readability). The [box-start]
and [box-end]
custom identifiers represent the box
area.
.box {
display: grid;
grid-template:
[box-start] "tagline actions" [box-end] /
[box-start] 1fr auto [box-end];
}
.box > *,
.box::before {
grid-area: box;
}
Passing a name with the -start
and -end
syntax into brackets defines an area for that name. This name, known as a custom ident, can be anything but words from the CSS spec should be avoided.
Logical placement values
One of the really interesting parts to observe in this last example is the use of logical values, like start
and end
, for placing elements. If the direction
or writing-mode
were to change, then the elements would reposition accordingly.
When the “right to left” direction is selected from the dropdown, the inline start and end positions are reversed. This layout is ready to accommodate languages, such as Arabic or Hebrew, that read from right to left without having to override any of the existing CSS.
Wrapping up
I hope you enjoyed these demos and that they provide some new ideas for your own project layouts—I’ve compiled a collection of examples you can check out over at CodePen. The amount of power packed into the CSS Grid spec is incredible. Take a minute to reflect on the days of using floats and a clearfix for primitive grid row design, then return to the present day and behold the glorious layout and display properties of today‘s CSS. To make these things work well is no easy task, so let’s applaud the members of the CSS working group. The web space continues to evolve and they continue to make it a fun place to build.
Now let’s release container queries and really get this party started.
The post Positioning Overlay Content with CSS Grid appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.