响应式设计

响应式网页设计(RWD)是一种网页设计方法,可以使网页在所有屏幕尺寸和分辨率上都能良好呈现,同时确保良好的可用性。这是设计多设备网络的方法。在本文中,我们将帮助你了解一些可用于掌握它的技术。

¥Responsive web design (RWD) is a web design approach to make web pages render well on all screen sizes and resolutions while ensuring good usability. It is the way to design for a multi-device web. In this article, we'll help you understand some techniques that can be used to master it.

先决条件: HTML 基础知识(研究 HTML 简介),以及 CSS 工作原理的概念(研究 CSS 第一步CSS 构建块)。
目标: 了解用于实现响应式设计的基本目的和 CSS 功能。

响应式设计的前身:移动网页设计

¥Precursor to responsive design: mobile web design

在响应式网页设计成为使网站在不同设备类型上运行的标准方法之前,网页开发者常常谈论移动网页设计、移动网页开发,有时甚至是移动友好的设计。这些基本上与响应式网页设计相同 - 目标是确保网站在布局、内容(文本和媒体)和性能方面能够在具有不同物理属性(屏幕尺寸、分辨率)的设备上正常运行。

¥Before responsive web design became the standard approach for making websites work across different device types, web developers used to talk about mobile web design, mobile web development, or sometimes, mobile-friendly design. These are basically the same as responsive web design — the goals are to make sure that websites work well across devices with different physical attributes (screen size, resolution) in terms of layout, content (text and media), and performance.

区别主要在于所涉及的设备以及可用于创建解决方案的技术:

¥The difference is mainly to do with the devices involved, and the technologies available to create solutions:

  • 我们曾经谈论台式机或移动设备,但现在有许多不同类型的设备可用,例如台式机、注意本电脑、移动设备、平板电脑、监视等。我们现在需要防御性地设计网站,而不是迎合几种不同的屏幕尺寸 以满足常见的屏幕尺寸和分辨率以及未知的情况。
  • 过去,移动设备的 CPU/GPU 和可用带宽都是低功耗的。有些不支持 CSS 甚至 HTML,因此,在提供设备能够处理的网站之前,通常会执行服务器端浏览器嗅探来确定设备/浏览器类型。移动设备通常提供非常简单、基本的体验,因为这是它们所能处理的全部。如今,移动设备能够处理与台式计算机相同的技术,因此此类技术不太常见。
    • 你仍然应该使用本文中讨论的技术来为移动用户提供合适的体验,因为仍然需要担心电池寿命和带宽等限制。
    • 用户体验也是一个问题。例如,旅游网站的移动用户可能只想检查航班时间和延误信息,而不是看到显示航班路径和公司历史的 3D 动画地球仪。然而,这可以使用响应式设计技术来处理。
  • 现代技术更适合创造响应式体验。例如,响应式图片/媒体技术 现在允许将适当的媒体提供给不同的设备,而不必依赖服务器端嗅探等技术。

引入响应式网页设计

¥Introducing responsive web design

HTML 本质上是响应式的,或者说是流畅的。如果你创建一个仅包含 HTML(不含 CSS)的网页,并调整窗口大小,浏览器将自动重排文本以适合视口。

¥HTML is fundamentally responsive, or fluid. If you create a web page containing only HTML, with no CSS, and resize the window, the browser will automatically reflow the text to fit the viewport.

虽然默认的响应行为听起来似乎不需要任何解决方案,但在宽显示器上全屏显示的长行文本可能难以阅读。如果通过 CSS 减少宽屏幕行长度(例如通过创建列或添加显着的填充),则对于缩小浏览器窗口或在移动设备上打开网站的用户来说,网站可能会看起来被压扁。

¥While the default responsive behavior may sound like no solution is needed, long lines of text displayed full screen on a wide monitor can be difficult to read. If wide screen line length is reduced with CSS, such as by creating columns or adding significant padding, the site may look squashed for the user who narrows their browser window or opens the site on a mobile device.

A layout with two columns squashed into a mobile size viewport.

通过设置固定宽度来创建不可调整大小的网页也不起作用;这会导致窄设备上的滚动条和宽屏幕上的空白空间过多。

¥Creating a non-resizable web page by setting a fixed width doesn't work either; that leads to scroll bars on narrow devices and too much empty space on wide screens.

响应式网页设计(RWD)是一种解决设备范围和设备尺寸的设计方法,无论内容是在平板电脑、手机、电视还是监视上查看,都可以自动适应屏幕。

¥Responsive web design, or RWD, is a design approach that addresses the range of devices and device sizes, enabling automatic adaption to the screen, whether the content is viewed on a tablet, phone, television, or watch.

响应式网页设计不是一项单独的技术,而是一种方法。它是一个术语,用于描述一组最佳实践,用于创建可以响应用于查看内容的任何设备的布局。

¥Responsive web design isn't a separate technology — it is an approach. It is a term used to describe a set of best practices used to create a layout that can respond to any device being used to view the content.

术语响应式设计 由伊森·马科特 (Ethan Marcotte) 于 2010 年创造 描述了使用流体网格、流体图片和媒体查询来创建响应式内容,如 Zoe Mickley Gillenwater 的书 灵活的网页设计 中所述。

¥The term responsive design, coined by Ethan Marcotte in 2010, described using fluid grids, fluid images, and media queries to create responsive content, as discussed in Zoe Mickley Gillenwater's book Flexible Web Design.

当时的建议是使用 CSS float 进行布局和媒体查询来查询浏览器宽度,为不同的断点创建布局。流体图片设置为不超过其容器的宽度;他们将 max-width 属性设置为 100%。当包含的柱变窄时,流体图片会按比例缩小,但当柱增长时,流体图片不会增长到大于其固有尺寸。这使得图片能够缩小以适应其内容,而不是溢出它,但如果容器变得比图片宽,则图片不会变大并变得像素化。

¥At the time, the recommendation was to use CSS float for layout and media queries to query the browser width, creating layouts for different breakpoints. Fluid images are set to not exceed the width of their container; they have their max-width property set to 100%. Fluid images scale down when their containing column narrows but do not grow larger than their intrinsic size when the column grows. This enables an image to scale down to fit its content, rather than overflow it, but not grow larger and become pixelated if the container becomes wider than the image.

现代 CSS 布局方法本质上是响应式的,并且自从 Gillenwater 的书和 Marcotte 的文章发布以来,我们在 Web 平台中内置了多种功能,使设计响应式网站变得更加容易。

¥Modern CSS layout methods are inherently responsive, and, since the publication of Gillenwater's book and Marcotte's article, we have a multitude of features built into the web platform to make designing responsive sites easier.

本文的其余部分将向你介绍在创建响应式网站时可能想要使用的各种 Web 平台功能。

¥The rest of this article will point you to the various web platform features you might want to use when creating a responsive site.

媒体查询

¥Media Queries

媒体查询 允许我们运行一系列测试(例如,用户的屏幕是否大于特定宽度或特定分辨率),并有选择地应用 CSS 来根据用户的需求适当设置页面样式。

¥Media queries allow us to run a series of tests (e.g. whether the user's screen is greater than a certain width, or a certain resolution) and apply CSS selectively to style the page appropriately for the user's needs.

例如,以下媒体查询测试当前网页是否显示为屏幕媒体(因此不是打印文档)以及视口是否至少为 80rem 宽。仅当这两件事为真时,才会应用 .container 选择器的 CSS。

¥For example, the following media query tests to see if the current web page is being displayed as screen media (therefore not a printed document) and the viewport is at least 80rem wide. The CSS for the .container selector will only be applied if these two things are true.

css
@media screen and (min-width: 80rem) {
  .container {
    margin: 1em 2em;
  }
}

你可以在样式表中添加多个媒体查询,调整整个布局或部分布局以最适合各种屏幕尺寸。引入媒体查询和更改布局的点称为断点。

¥You can add multiple media queries within a stylesheet, tweaking your whole layout or parts of it to best suit the various screen sizes. The points at which a media query is introduced, and the layout changed, are known as breakpoints.

使用媒体查询时的常见方法是为窄屏幕设备(例如手机)创建简单的单列布局,然后检查更宽的屏幕,并在知道有足够的屏幕宽度来处理时实现多列布局 它。移动优先设计被称为移动优先设计。

¥A common approach when using Media Queries is to create a simple single-column layout for narrow-screen devices (e.g. mobile phones), then check for wider screens and implement a multiple-column layout when you know that you have enough screen width to handle it. Designing for mobile first is known as mobile first design.

如果使用断点,最佳实践鼓励使用 相对单位 而不是单个设备的绝对大小来定义媒体查询断点。

¥If using breakpoints, best practices encourage defining media query breakpoints with relative units rather than absolute sizes of an individual device.

媒体查询块中定义的样式有不同的方法;从使用媒体查询到基于浏览器大小范围的 <link> 样式表,再到仅包含自定义属性变量来存储与每个断点关联的值。

¥There are different approaches to the styles defined within a media query block; ranging from using media queries to <link> style sheets based on browser size ranges to only including custom properties variables to store values associated with each breakpoint.

如需了解更多信息,请参阅 媒体查询 的 MDN 文档。

¥Find out more in the MDN documentation for Media Queries.

媒体查询可以帮助 RWD,但不是必需的。无需查询即可使用灵活的网格、相对单位以及最小和最大单位值。

¥Media queries can help with RWD, but are not a requirement. Flexible grids, relative units, and minimum and maximum unit values can be used without queries.

响应式布局技术

¥Responsive layout technologies

响应式网站建立在灵活的网格上,这意味着你不需要使用像素完美的布局来定位所有可能的设备尺寸。

¥Responsive sites are built on flexible grids, meaning you don't need to target every possible device size with pixel perfect layouts.

通过使用灵活的网格,你可以更改功能或添加断点,并在内容开始看起来很糟糕的地方更改设计。例如,为了确保行长度不会随着屏幕尺寸的增加而变得难以阅读,你可以使用 columns;如果一个框在变窄时被压扁,每行有两个单词,你可以设置一个断点。

¥By using a flexible grid, you can change a feature or add in a breakpoint and change the design at the point where the content starts to look bad. For example, to ensure line lengths don't become unreadably long as the screen size increases you can use columns; if a box becomes squashed with two words on each line as it narrows you can set a breakpoint.

默认情况下,包括 多列布局弹性盒网格 在内的多种布局方法都是响应式的。他们都假设你正在尝试创建一个灵活的网格,并为你提供更简单的方法来做到这一点。

¥Several layout methods, including Multiple-column layout, Flexbox, and Grid are responsive by default. They all assume that you are trying to create a flexible grid and give you easier ways to do so.

多科尔

¥Multicol

使用 multicol,你可以指定 column-count 来指示你希望将内容拆分成的最大列数。然后浏览器计算出这些的大小,该大小将根据屏幕大小而变化。

¥With multicol, you specify a column-count to indicate the maximum number of columns you want your content to be split into. The browser then works out the size of these, a size that will change according to the screen size.

css
.container {
  column-count: 3;
}

如果你指定 column-width,则你指定的是最小宽度。浏览器将创建尽可能多的该宽度的列,以适合容器,然后共享所有列之间的剩余空间。因此,列数将根据空间大小而变化。

¥If you instead specify a column-width, you are specifying a minimum width. The browser will create as many columns of that width as will comfortably fit into the container, then share out the remaining space between all the columns. Therefore the number of columns will change according to how much space there is.

css
.container {
  column-width: 10em;
}

你可以使用 columns 简写来提供最大列数和最小列宽。这可以确保行长度不会随着屏幕尺寸的增加而变得难以阅读,或者随着屏幕尺寸的减小而变得太窄。

¥You can use the columns shorthand to provide a maximum number of columns and a minimum column width. This can ensure line lengths don't become unreadably long as the screen size increases or too narrow as the screen size decreases.

弹性盒

¥Flexbox

在 flexbox 中,flex 项目会缩小或增大,根据其容器中的空间在项目之间分配空间。通过更改 flex-growflex-shrink 的值,你可以指示当项目周围遇到更多或更少的空间时你希望项目如何表现。

¥In flexbox, flex items shrink or grow, distributing space between the items according to the space in their container. By changing the values for flex-grow and flex-shrink you can indicate how you want the items to behave when they encounter more or less space around them.

在下面的示例中,每个 Flex 项目将在 Flex 容器中占用相同的空间,使用布局主题 弹性盒:弹性项目的灵活尺寸 中所述的 flex: 1 简写。

¥In the example below the flex items will each take an equal amount of space in the flex container, using the shorthand of flex: 1 as described in the layout topic Flexbox: Flexible sizing of flex items.

css
.container {
  display: flex;
}

.item {
  flex: 1;
}

注意:作为示例,我们在上面使用 Flexbox 构建了一个简单的响应式布局。我们使用断点在屏幕增长时切换到多列,并用 max-width 限制主要内容的大小:example, 源代码.

¥Note: As an example, we have built a simple responsive layout above using flexbox. We use a breakpoint to switch to multiple columns when the screen grows, and limit the size of the main content with max-width: example, source code.

CSS 网格

¥CSS grid

在 CSS 网格布局中,fr 单元允许在网格轨道上分配可用空间。下一个示例创建一个网格容器,其中包含三个大小为 1fr 的轨道。这将创建三列轨道,每列轨道占用容器中可用空间的一部分。你可以在 带有 fr 单元的灵活网格 下的“学习布局网格”主题中找到有关此方法创建网格的更多信息。

¥In CSS grid layout the fr unit allows the distribution of available space across grid tracks. The next example creates a grid container with three tracks sized at 1fr. This will create three column tracks, each taking one part of the available space in the container. You can find out more about this approach to create a grid in the Learn Layout grids topic, under Flexible grids with the fr unit.

css
.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

注意:网格布局版本更加简单,因为我们可以在 .wrapper 上定义列:example, 源代码.

¥Note: The grid layout version is even simpler as we can define the columns on the .wrapper: example, source code.

响应式图片/媒体

¥Responsive images/media

为了确保媒体永远不会大于其响应容器,可以使用以下方法:

¥To ensure media is never larger than its responsive container, the following approach can be used:

css
img,
picture,
video {
  max-width: 100%;
}

这可以缩放介质以确保它们永远不会溢出容器。使用单个大图片并将其缩小以适应小型设备会因为下载大于所需的图片而浪费带宽。

¥This scales media to ensure they never overflow their containers. Using a single large image and scaling it down to fit small devices wastes bandwidth by downloading images larger than what is needed.

响应式图片,使用 <picture> 元素以及 <img> srcsetsizes 属性,可以提供针对用户视口和设备分辨率的图片。例如,你可以在移动设备上包含方形图片,但在桌面上显示与横向图片相同的场景。

¥Responsive Images, using the <picture> element and the <img> srcset and sizes attributes enables serving images targeted to the user's viewport and the device's resolution. For example, you can include a square image for mobile, but show the same scene as a landscape image on desktop.

<picture> 元素可以与 "hints"(描述图片最适合的屏幕尺寸和分辨率的元数据)一起提供多种尺寸,浏览器将为每个设备选择最合适的图片,确保用户下载合适的图片尺寸 对于他们正在使用的设备。将 <picture>max-width 一起使用可以消除通过媒体查询调整图片大小的需要。它允许将具有不同 aspect ratios 的图片定位到不同的视口大小。

¥The <picture> element enables providing multiple sizes along with "hints" (metadata that describes the screen size and resolution the image is best suited for), and the browser will choose the most appropriate image for each device, ensuring that a user will download an image size appropriate for the device they are using. Using <picture> along with max-width removes the need for sizing images with media queries. It enables targeting images with different aspect ratios to different viewport sizes.

你还可以对不同尺寸的图片进行艺术指导,从而为不同的屏幕尺寸提供不同的裁剪或完全不同的图片。

¥You can also art direct images used at different sizes, thus providing a different crop or completely different image to different screen sizes.

你可以在 MDN 上找到详细的 学习 HTML 部分中的响应式图片指南

¥You can find a detailed guide to Responsive Images in the Learn HTML section here on MDN.

其他有用的提示:

¥Other useful tips:

  • 始终确保为你的网站图片使用适当的图片格式(例如 PNG 或 JPG),并确保在将它们放到网站上之前使用图形编辑器优化文件大小。
  • 你可以利用 gradientsshadows 等 CSS 功能来实现视觉效果,而无需使用图片。
  • 你可以在嵌套在 <video>/<audio> 元素内的 <source> 元素的媒体属性内使用媒体查询,以根据不同设备的情况提供视频/音频文件(响应式视频/音频)。

响应式排版

¥Responsive typography

响应式排版描述了改变媒体查询中的字体大小或使用视口单位来反映更少或更多的屏幕空间。

¥Responsive typography describes changing font sizes within media queries or using viewport units to reflect lesser or greater amounts of screen real estate.

使用媒体查询进行响应式排版

¥Using media queries for responsive typography

在此示例中,我们希望将 1 级标题设置为 4rem,这意味着它将是基本字体大小的四倍。这真是一个大标题!我们只希望这个巨型标题出现在较大的屏幕尺寸上,因此,如果我们知道用户的屏幕尺寸至少为 1200px,我们首先创建一个较小的标题,然后使用媒体查询用较大的尺寸覆盖它。

¥In this example, we want to set our level 1 heading to be 4rem, meaning it will be four times our base font size. That's a really large heading! We only want this jumbo heading on larger screen sizes, therefore we first create a smaller heading then use media queries to overwrite it with the larger size if we know that the user has a screen size of at least 1200px.

css
html {
  font-size: 1em;
}

h1 {
  font-size: 2rem;
}

@media (min-width: 1200px) {
  h1 {
    font-size: 4rem;
  }
}

我们已经使用上述方法编辑了上面的响应式网格示例,以包含响应式类型。你可以看到当布局变为两列版本时标题如何切换大小。

¥We have edited our responsive grid example above to also include responsive type using the method outlined. You can see how the heading switches sizes as the layout goes to the two column version.

在移动设备上,标题较小:

¥On mobile the heading is smaller:

A stacked layout with a small heading size.

然而,在桌面上,我们看到更大的标题尺寸:

¥On desktop, however, we see the larger heading size:

A two column layout with a large heading.

注意:请参阅此示例:example, 源代码.

¥Note: See this example in action: example, source code.

正如这种排版方法所示,你不需要将媒体查询限制为仅更改页面布局。它们可用于调整任何元素,使其在不同的屏幕尺寸下更可用或更有吸引力。

¥As this approach to typography shows, you do not need to restrict media queries to only changing the layout of the page. They can be used to tweak any element to make it more usable or attractive at alternate screen sizes.

使用视口单位进行响应式排版

¥Using viewport units for responsive typography

视口单元 vw 还可用于启用响应式排版,无需使用媒体查询设置断点。1vw 等于视口宽度的百分之一,这意味着如果你使用 vw 设置字体大小,它将始终与视口的大小相关。

¥Viewport units vw can also be used to enable responsive typography, without the need for setting breakpoints with media queries. 1vw is equal to one percent of the viewport width, meaning that if you set your font size using vw, it will always relate to the size of the viewport.

css
h1 {
  font-size: 6vw;
}

执行上述操作的问题在于,用户失去了使用 vw 单位缩放任何文本集的能力,因为该文本始终与视口的大小相关。因此,你永远不应该单独使用视口单位设置文本。

¥The problem with doing the above is that the user loses the ability to zoom any text set using the vw unit, as that text is always related to the size of the viewport. Therefore you should never set text using viewport units alone.

有一个解决方案,它涉及使用 calc()。如果将 vw 单位添加到使用固定大小(例如 emrem)的值集,则文本仍然可以缩放。本质上,vw 单位在缩放值的基础上添加:

¥There is a solution, and it involves using calc(). If you add the vw unit to a value set using a fixed size such as ems or rems then the text will still be zoomable. Essentially, the vw unit adds on top of that zoomed value:

css
h1 {
  font-size: calc(1.5rem + 3vw);
}

这意味着我们只需要指定标题的字体大小一次,而不是为移动设备设置它并在媒体查询中重新定义它。随着视口大小的增加,字体逐渐增大。

¥This means that we only need to specify the font size for the heading once, rather than set it up for mobile and redefine it in the media queries. The font then gradually increases as you increase the size of the viewport.

注意:请参阅实际操作的示例:example, 源代码.

¥Note: See an example of this in action: example, source code.

视口元标记

¥The viewport meta tag

如果你查看响应式页面的 HTML 源代码,你通常会在文档的 <head> 中看到以下 <meta> 标记。

¥If you look at the HTML source of a responsive page, you will usually see the following <meta> tag in the <head> of the document.

html
<meta name="viewport" content="width=device-width,initial-scale=1" />

viewport 元标记告诉移动浏览器应将视口的宽度设置为设备宽度,并将文档缩放至其预期大小的 100%,这会以你预期的移动优化大小显示文档。

¥This viewport meta tag tells mobile browsers that they should set the width of the viewport to the device width, and scale the document to 100% of its intended size, which shows the document at the mobile-optimized size that you intended.

为什么需要这个?因为移动浏览器往往会谎报其视口宽度。

¥Why is this needed? Because mobile browsers tend to lie about their viewport width.

这个元标签的存在是因为当智能手机首次出现时,大多数网站都没有针对移动设备进行优化。因此,移动浏览器会将视口宽度设置为 980 像素,以该宽度渲染页面,并将结果显示为桌面布局的缩小版本。用户可以放大和平移网站来查看他们感兴趣的部分,但看起来很糟糕。

¥This meta tag exists because when smartphones first arrived, most sites were not mobile optimized. The mobile browser would, therefore, set the viewport width to 980 pixels, render the page at that width, and show the result as a zoomed-out version of the desktop layout. Users could zoom in and pan around the website to view the bits they were interested in, but it looked bad.

通过设置 width=device-width,你将使用设备的实际宽度覆盖移动设备的默认值,例如 Apple 的默认值 width=980px。如果没有它,带有断点和媒体查询的响应式设计可能无法在移动浏览器上按预期工作。如果你有一个窄屏幕布局,其视口宽度为 480 像素或更小,但设备显示宽度为 980 像素,则用户将看不到你的窄屏幕布局。

¥By setting width=device-width you are overriding a mobile device's default, like Apple's default width=980px, with the actual width of the device. Without it, your responsive design with breakpoints and media queries may not work as intended on mobile browsers. If you've got a narrow screen layout that kicks in at 480px viewport width or less, but the device is saying it is 980px wide, that user will not see your narrow screen layout.

因此,你应该始终在文档的头部包含视口元标记。

¥So you should always include the viewport meta tag in the head of your documents.

概括

¥Summary

响应式设计是指响应其查看环境的站点或应用设计。它包含许多 CSS 和 HTML 功能和技术,现在基本上就是我们默认构建网站的方式。考虑一下你在手机上访问的网站 - 遇到桌面版本缩小的网站,或者你需要横向滚动才能找到内容的网站可能相当不寻常。这是因为网络已经转向这种响应式设计方法。

¥Responsive design refers to a site or application design that responds to the environment in which it is viewed. It encompasses a number of CSS and HTML features and techniques and is now essentially just how we build websites by default. Consider the sites that you visit on your phone — it is probably fairly unusual to come across a site that is the desktop version scaled down, or where you need to scroll sideways to find things. This is because the web has moved to this approach of designing responsively.

借助你在这些课程中学到的布局方法,实现响应式设计也变得更加容易。如果你是当今 Web 开发的新手,那么你可以使用比响应式设计早期更多的工具。因此,值得检查你所使用的任何材料的年龄。虽然历史文章仍然有用,但现代 CSS 和 HTML 的使用使得创建优雅且有用的设计变得更加容易,无论访问者使用什么设备查看网站。

¥It has also become much easier to achieve responsive designs with the help of the layout methods you have learned in these lessons. If you are new to web development today you have many more tools at your disposal than in the early days of responsive design. It is therefore worth checking the age of any materials you are using. While the historical articles are still useful, modern use of CSS and HTML makes it far easier to create elegant and useful designs, no matter what device your visitor views the site with.

也可以看看

¥See also