Positioning Overlay Content material with CSS Grid

No Comments

Not information to any internet developer in 2021: CSS Grid is an extremely highly effective instrument for creating advanced, distinct two-dimensional trendy internet layouts.

Not too long ago, I’ve been experimenting with CSS Grid and alignment properties to create part layouts that include a number of overlapping parts. These layouts could possibly be styled utilizing absolute positioning and a mixture of offset values (prime, proper, backside, left), detrimental margins, and transforms. However, with CSS Grid, positioning overlay parts could be constructed utilizing extra logical, readable properties and values. The next are a number of examples of the place these grid properties turn out to be useful.

It can assist to learn up on grid-template-areas and grid-area properties should you’re not but aware of them.

Increasing pictures inside restricted dimensions

CodePen Embed Fallback

Within the demo, there’s a checkbox that toggles the overflow visibility in order that we will see the place the picture dimensions increase past the container on bigger viewport widths.

Right here’s a typical hero part with a headline overlapping a picture. Though the picture is capped with a max-width, it scales as much as be fairly tall on desktop. Due to this, the content material technique workforce has requested that a few of the pertinent web page content material beneath the hero stay seen within the viewport as a lot as potential. Combining this format approach and a fluid container max-height utilizing the CSS clamp() perform, we will develop one thing that adjusts primarily based on the accessible viewport house whereas anchoring the hero picture to the middle of the container.

CSS clamp(), together with the min() and max() comparability features, are well-supported in all trendy browsers. Haven’t used them? Ahmad Shadeed conducts a incredible deep dive in this text.

Open this Pen and resize the viewport width. Primarily based on the picture dimensions, the container top expands till it hits a most top. Discover that the picture continues to develop whereas remaining centered within the container. Resize the viewport top and the container will flex between its max-height’s decrease and higher sure values outlined within the clamp() perform.

Previous to utilizing grid for the format kinds, I may need tried absolute positioning on the picture and title, used an side ratio padding trick to create a responsive top, and object-fit to retain the ratio of the picture. One thing like this might get it there:

.container {
place: relative;
max-height: clamp(400px, 50vh, 600px);
}

.container::earlier than {
content material: ”;
show: block;
padding-top: 52.25%;
}

.container > * {
max-width: 1000px;
}

.container .picture {
place: absolute;
prime: 0;
left: 50%;
rework: translateX(-50%);
width: 100%;
top: 100%;
object-fit: cowl;
}

.container .title {
place: absolute;
prime: 50%;
left: 50%;
rework: translate(-50%, -50%);
width: 100%;
text-align: heart;
}

Possibly it’s potential to whittle the code down some extra, however there’s nonetheless a great chunk of styling wanted. Managing the identical responsive format with CSS Grid will simplify these format model guidelines whereas making the code extra readable. Test it out within the following iteration:

.container {
show: grid;
grid-template: “container”;
place-items: heart;
place-content: heart;
overflow: hidden;
max-height: clamp(450px, 50vh, 600px);
}

.container > * {
grid-area: container;
max-width: 1000px;
}

place-content: heart instructs the picture to proceed rising out from the center of the container. Take away this line and see that, whereas the picture continues to be vertically centered by way of place-items, as soon as the max-height is reached, the picture will persist with the highest of the container block and go on scaling past its backside. Set place-content: finish heart and also you’ll see the picture spill excessive of the container.

This habits could appear conceptually just like making use of object-fit: cowl on a picture as a styling methodology for preserving its intrinsic ratio whereas resizing to fill its content-box dimensions (it was utilized within the absolute place iteration). Nonetheless, on this grid context, the picture aspect governs the peak of its dad or mum and, as soon as the dad or mum’s max-height is reached, the picture continues to increase, sustaining its ratio, and stays fully seen if the dad or mum overflow is proven. object-fit might even be used with the aspect-ratio property right here to create a constant side ratio sample for the hero picture:

.container .picture {
width: 100%;
top: auto;
object-fit: cowl;
aspect-ratio: 16 / 9;
}

The overlay grid-area

Shifting on to the container’s direct youngsters, grid-area arranges every of them in order that they overlap the identical house. On this instance, grid-template-areas with the named grid space makes the code just a little extra readable and works properly as a sample for different overlay-style layouts inside a part library. That being stated, it’s potential to get this identical outcome by eradicating the template rule and, as a substitute of grid-area: container, utilizing integers:

.container > * {
grid-area: 1 / 1;
}

That is shorthand for grid-row-start, grid-column-start, grid-row-end, and grid-column-end. For the reason that siblings on this demo all share the identical single row/column space, solely the beginning strains should be set for the specified outcome.

Setting place-self to put itself

One other frequent overlay sample could be seen on picture carousels. Interactive parts are sometimes positioned on prime of the carousel viewport. I’ve prolonged the primary demo and changed the static hero picture with a carousel.

CodePen Embed Fallback

Identical story as earlier than: This format might fall again on absolute positioning and use integer values in a handful of properties to push and pull parts round their dad or mum container. As a substitute, we’ll reuse the grid format rulesets from the earlier demo. As soon as utilized, it seems as you would possibly anticipate: the entire little one parts are centered contained in the container, overlapping each other.

With place-items: heart declared on the container, all of its direct youngsters will overlap each other.

The subsequent step is to set alignment values on particular person parts. The place-self property—shorthand for align-self and justify-self—offers granular management over the place of a single merchandise contained in the container. Listed here are the format kinds altogether:

.container {
show: grid;
grid-template:”container”;
place-items: heart;
place-content: heart;
overflow: hidden;
max-height: clamp(450px, 50vh, 600px);
}

.container > * {
grid-area: container;
max-width: 1000px;
}

.title {
place-self: begin heart;
}

.carousel-control.prev {
place-self: heart left;
}

.carousel-control.subsequent {
place-self: heart proper;
}

.carousel-dots {
place-self: finish heart;
}

There’s only one small downside: The title and carousel dot indicators get pulled out into the overflow when the picture exceeds the container dimensions.

To correctly include these parts throughout the dad or mum, a grid-template-row worth must be 100% of the container, set right 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 are going to see once more later on this article).

.container {
grid-template: “container” 1fr;
}

After offering that little replace, the overlay parts keep throughout the dad or mum container, even when the carousel pictures unfold past the carousel’s borders.

Alignment and named grid-template-areas

Let’s use the earlier overlay format strategies for yet another instance. On this demo, every field incorporates parts positioned in several areas on prime of a picture.

CodePen Embed Fallback

For the primary iteration, a named template space is asserted to overlay the kids on the dad or mum aspect house, just like the earlier demos:

.field {
show: grid;
grid-template-areas: “field”;
}

.field > *,
.field::earlier than {
grid-area: field;
}

The picture and semi-transparent overlay now cowl the field space, however these model guidelines additionally stretch the opposite objects over the whole house. This looks as if the proper time for place-self to pepper these parts with some alignment magic!

.tag {
place-self: begin;
}

.title {
place-self: heart;
}

.tagline {
place-self: finish begin;
}

.actions {
place-self: finish;
}

That‘s wanting nice! Each aspect is positioned of their outlined locations over the picture as meant. Nicely, virtually. There’s a little bit of nuance to the underside space the place the tagline and motion buttons reside. Hover over a picture to disclose the tagline. This would possibly look high-quality with a brief string of textual content on a desktop display screen, but when the tagline turns into longer (or the bins within the viewport smaller), it would finally prolong behind the motion buttons.

Notice how the tagline within the first field on the second row overlaps the motion buttons.

To wash this up, the grid-template-areas use named areas for the tagline and actions. The grid-template-columns rule is launched in order that the actions container solely scales to accommodate the scale of its buttons whereas the tagline fills in the remainder of the inline space utilizing the 1fr worth.

.field {
show: grid;
grid-template-areas: “tagline actions”;
grid-template-columns: 1fr auto;
}

This may also be mixed with the grid-template shorthand. The column values are outlined after a slash, like so:

.field {
grid-template: “tagline actions” / 1fr auto;
}

The grid-area is then transformed to integers now that the “field” key phrase has been eliminated.

.field > *,
.field::earlier than {
grid-area: 1 / 1 / -1 / -1;
}

Every thing ought to look the way in which it did earlier than. Now for the final touch. The tagline and actions key phrases are set as their respective aspect grid-area values:

.tagline {
grid-area: tagline;
place-self: finish begin;
}

.actions {
grid-area: actions;
place-self: finish;
}

Now, when hovering over the playing cards within the demo, the tagline wraps to a number of strains when the textual content turns into too lengthy, somewhat than pushing previous the motion buttons prefer it did earlier than.

Named grid strains

Trying again on the first iteration of this code, I actually favored having the default grid-area set to the field key phrase. There’s a strategy to get that again.

I’m going add some named grid strains to the template. Within the grid-template rule beneath, the primary line defines the named template areas, which additionally represents the row. After the slash are the specific column sizes (moved to a brand new line for readability). The [box-start] and [box-end] customized identifiers signify the field space.

.field {
show: grid;
grid-template:
[box-start] “tagline actions” [box-end] /
[box-start] 1fr auto [box-end];
}

.field > *,
.field::earlier than {
grid-area: field;
}

Passing a reputation with the -start and -end syntax into brackets defines an space for that title. This title, referred to as a customized ident, could be something however phrases from the CSS spec needs to be prevented.

Logical placement values

One of many actually fascinating components to watch on this final instance is using logical values, like begin and finish, for putting parts. If the course or writing-mode have been to alter, then the weather would reposition accordingly.

When the “proper to left” course is chosen from the dropdown, the inline begin and finish positions are reversed. This format is able to accommodate languages, equivalent to Arabic or Hebrew, that learn from proper to left with out having to override any of the present CSS.

Wrapping up

I hope you loved these demos and that they supply some new concepts in your personal mission layouts—I’ve compiled a assortment of examples you possibly can take a look at over at CodePen. The quantity of energy packed into the CSS Grid spec is unbelievable. Take a minute to replicate on the times of utilizing floats and a clearfix for primitive grid row design, then return to the current day and behold the fantastic format and show properties of at present‘s CSS. To make this stuff work properly is not any simple activity, so let’s applaud the members of the CSS working group. The net house continues to evolve and so they proceed to make it a enjoyable place to construct.

Now let’s launch container queries and actually get this social gathering began.

The submit Positioning Overlay Content material with CSS Grid appeared first on CSS-Methods. You’ll be able to help CSS-Methods by being an MVP Supporter.

    About Marketing Solution Australia

    We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

    Request a free quote

    We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

    Subscribe to our newsletter!

    More from our blog

    See all posts

    Leave a Comment