搜尋
首頁web前端css教學用CSS網格定位覆蓋內容

Positioning Overlay Content with CSS Grid

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.

以上是用CSS網格定位覆蓋內容的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Draggin'和droppin'在反應中Draggin'和droppin'在反應中Apr 17, 2025 am 11:52 AM

React生態系統為我們提供了許多庫,所有庫都集中在拖放的相互作用上。我們有反應,反應,可愛dnd,

快速軟件快速軟件Apr 17, 2025 am 11:49 AM

最近有一些關於快速軟件的完美互連的事情。

帶有背景折疊的嵌套梯度帶有背景折疊的嵌套梯度Apr 17, 2025 am 11:47 AM

我可以說我經常使用背景折疊。 IT Wager IT幾乎從未在日常CSS工作中使用。但是在斯特凡·朱迪斯(Stefan Judis)的帖子中,我想起了它,

使用React Hooks使用requestAnimationFrame使用React Hooks使用requestAnimationFrameApr 17, 2025 am 11:46 AM

使用RequestAnimationFrame進行動畫化應該很容易,但是如果您還沒有徹底閱讀React的文檔,那麼您可能會遇到一些事情

需要滾動到頁面頂部嗎?需要滾動到頁面頂部嗎?Apr 17, 2025 am 11:45 AM

向用戶提供此鏈接的最簡單方法是針對元素上的ID的鏈接。如此...

最好的(GraphQl)API是您編寫的API最好的(GraphQl)API是您編寫的APIApr 17, 2025 am 11:36 AM

聽著,我不是GraphQL專家,但我確實喜歡與之合作。作為前端開發人員,它向我曝光數據的方式非常酷。它就像一個菜單

在保留邊框半徑的同時,擴展盒子的各種方法在保留邊框半徑的同時,擴展盒子的各種方法Apr 17, 2025 am 11:19 AM

我最近注意到Codepen的一個有趣的更改:在懸停在主頁上的筆時,有一個矩形,圓角在後面擴展。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具