찾다
웹 프론트엔드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으로 문의하세요.
@keyframes 및 @Media와 같이 @Rules는 얼마나 많은 특이성을 가지고 있습니까?@keyframes 및 @Media와 같이 @Rules는 얼마나 많은 특이성을 가지고 있습니까?Apr 18, 2025 am 11:34 AM

나는 다른 날이 질문을 받았다. 나의 첫 번째 생각은 : 이상한 질문입니다! 특이성은 선택기에 관한 것이며 At-Rules는 선택기가 아니므로 ... 무의미합니까?

@Media 및 @Support 쿼리를 중첩 할 수 있습니까?@Media 및 @Support 쿼리를 중첩 할 수 있습니까?Apr 18, 2025 am 11:32 AM

그렇습니다. 당신은 할 수 있습니다. 그리고 그것은 실제로 어떤 순서로 중요하지 않습니다. CSS 전 처리기가 필요하지 않습니다. 일반 CSS에서 작동합니다.

빠른 Gulp 캐시 파열빠른 Gulp 캐시 파열Apr 18, 2025 am 11:23 AM

CSS 및 JavaScript (및 이미지 및 글꼴 등)와 같은 자산에 멀리 떨어진 캐시 헤더를 설정해야합니다. 브라우저를 알려줍니다

CSS의 품질과 복잡성을 모니터링하는 스택을 찾아CSS의 품질과 복잡성을 모니터링하는 스택을 찾아Apr 18, 2025 am 11:22 AM

많은 개발자들은 CSS 코드베이스를 유지하는 방법에 대해 글을 썼지 만 코드베이스의 품질을 어떻게 측정하는지에 대해 많은 글을 쓰지 않습니다. 물론, 우리는 가지고 있습니다

Datalist는 가치를 시행하지 않고 값을 제안하는 것입니다Datalist는 가치를 시행하지 않고 값을 제안하는 것입니다Apr 18, 2025 am 11:08 AM

짧고 임의의 텍스트를 수락 해야하는 양식이 있습니까? 이름이나 다른 것 같습니다. 정확히 무엇을위한 것입니다. 많은 것이 있습니다

취리히에서 열린 전면 회의취리히에서 열린 전면 회의Apr 18, 2025 am 11:03 AM

나는 프론트 컨퍼런스를 위해 스위스 취리히로 향하게되어 매우 기쁩니다 (그 이름과 URL을 사랑합니다!). 나는 전에 스위스에 가본 적이 없기 때문에 나는 흥분했다

CloudFlare Workers와 함께 풀 스택 서버리스 애플리케이션 구축CloudFlare Workers와 함께 풀 스택 서버리스 애플리케이션 구축Apr 18, 2025 am 10:58 AM

소프트웨어 개발에서 제가 가장 좋아하는 개발 중 하나는 서버리스의 출현이었습니다. 세부 사항에 푹 빠지는 경향이있는 개발자로서

NUXT 응용 프로그램에서 동적 경로 생성NUXT 응용 프로그램에서 동적 경로 생성Apr 18, 2025 am 10:53 AM

이 게시물에서는 들어오는 데이터를 위해 동적 경로를 만드는 방법을 보여주기 위해 NetLify에 구축하고 배포 한 전자 상거래 상점 데모를 사용합니다. 상당히입니다

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기