使用现代CSS构建典型部分设计

The following design might be simple to create in a tool like Figma, but getting them to work fluidly in the browser is a different story. It’s not complicated, but there are a few things that we need to consider.

以下设计在像 Figma 这样的工具中可能很简单,但在浏览器中流畅地工作是另一回事。这并不复杂,但我们需要考虑一些事情。

Take a look at the following design:

看看以下设计:

We have two main areas here to work on:

我们在这里有两个主要的工作领域:

  • The section’s header (icon, title, and description)
  • 部分的标题(图标、标题和描述)
  • The section’s content grid (cards)
  • 部分的内容网格(卡片)

How would you build this in CSS? Let’s find out.

你会如何在CSS中构建这个?让我们来看看。

Let’s start with the HTML markup:

让我们从HTML标记开始:

<section class="section"> <header class="section-header"> </header> <div class="section-content"> <div class="card"></div> <div class="card"></div> <div class="card"></div> </div>
</section>

And the CSS:

以及 CSS:

.section { display: grid; grid-template-columns: 1fr; gap: 1rem; @media (min-width: 600px) { grid-template-columns: 170px 1fr; }
}

Here is a working demo. Try resizing the container, items will wrap onto a new line. It works fine, but it can be improved.

这是一个工作演示。尝试调整容器大小,项目将换行。它工作得很好,但可以改进。

Card title

卡片标题

Card description

卡片描述

Card title

卡片标题

Card description

卡片描述

Card title

卡片标题

Card description

卡片描述

When we have more than 3 items on the largest viewport size, the 4th item will wrap into a new line.

当我们在最大视口大小上有超过3个项目时,第4个项目将换行。

Take a look:

看看:

Card title

卡片标题

Card description

卡片描述

Card title

卡片标题

Card description

卡片描述

Card title

卡片标题

Card description

卡片描述

Card title

卡片标题

Card description

卡片描述

There’s no direct way to detect orphaned items in CSS. In our case, we can change the layout by using CSS :has().

在CSS中没有直接的方法来检测孤立的项目。在我们的案例中,我们可以通过使用CSS :has() 来改变布局。

Let’s explore the solution.

让我们探索解决方案。

The solution

解决方案

I used a simple condition combined with quantity queries and got help from this awesome quantity queries tool by Temani Afif.

我使用了一个简单的条件,结合了数量查询,并得到了Temani Afif提供的这个很棒的数量查询工具的帮助。

.section { display: grid; grid-template-columns: 1fr; gap: 1rem; @media (min-width: 600px) { grid-template-columns: 170px 1fr;...
开通本站会员,查看完整译文。

- 위키
Copyright © 2011-2025 iteam. Current version is 2.147.1. UTC+08:00, 2025-11-03 17:48
浙ICP备14020137号-1 $방문자$