图片、媒体和表单元素

在本课中,我们将了解 CSS 中如何处理某些特殊元素。就使用 CSS 设置样式的能力而言,图片、其他媒体和表单元素的行为与常规框略有不同。了解什么是可能的、什么是不可能的可以避免一些挫败感,本课程将重点介绍你需要了解的一些主要内容。

¥In this lesson we will take a look at how certain special elements are treated in CSS. Images, other media, and form elements behave a little differently from regular boxes in terms of your ability to style them with CSS. Understanding what is and isn't possible can save some frustration, and this lesson will highlight some of the main things that you need to know.

先决条件: 基本软件已安装处理文件 的基础知识、HTML 基础知识(学习 HTML 简介)以及 CSS 工作原理的想法(学习 CSS 第一步)。
目标: 了解使用 CSS 设计样式时某些元素的异常行为方式。

替换的元素

¥Replaced elements

图片和视频被描述为 被替换的元素。这意味着 CSS 不能影响这些元素的内部布局 - 只能影响它们在页面上其他元素中的位置。然而,正如我们将看到的,CSS 可以对图片执行多种操作。

¥Images and video are described as replaced elements. This means that CSS cannot affect the internal layout of these elements — only their position on the page amongst other elements. As we will see however, there are various things that CSS can do with an image.

某些替换元素(例如图片和视频)也被描述为具有 aspect ratio。这意味着它具有水平 (x) 和垂直 (y) 维度的大小,并且默认情况下将使用文件的固有维度显示。

¥Certain replaced elements, such as images and video, are also described as having an aspect ratio. This means that it has a size in both the horizontal (x) and vertical (y) dimensions, and will be displayed using the intrinsic dimensions of the file by default.

调整图片大小

¥Sizing images

正如你从这些课程中已经知道的那样,CSS 中的所有内容都会生成一个盒子。如果将图片放置在任一方向上小于或大于图片文件的固有尺寸的框中,则该图片将显示为小于该框,或者溢出该框。你需要决定溢出会发生什么。

¥As you already know from following these lessons, everything in CSS generates a box. If you place an image inside a box that is smaller or larger than the intrinsic dimensions of the image file in either direction, it will either appear smaller than the box, or overflow the box. You need to make a decision about what happens with the overflow.

在下面的示例中,我们有两个框,大小均为 200 像素:

¥In the example below we have two boxes, both 200 pixels in size:

  • 其中一个包含小于 200 像素的图片 — 它比框小,并且不会拉伸以填充它。
  • 另一个大于 200 像素并溢出框。

那么对于溢出问题我们能做什么呢?

¥So what can we do about the overflowing issue?

正如我们在 我们上一课 中了解到的,一种常见的技术是将图片的 max-width 设为 100%。这将使图片的尺寸变得比框小,但不大于框。此技术也适用于其他替换元素,例如 <video><iframe>

¥As we learned in our previous lesson, a common technique is to make the max-width of an image 100%. This will enable the image to become smaller in size than the box but not larger. This technique will also work with other replaced elements such as <video>s, or <iframe>s.

尝试将 max-width: 100% 添加到上例中的 <img> 元素中。你将看到较小的图片保持不变,但较大的图片变得更小以适合盒子。

¥Try adding max-width: 100% to the <img> element in the example above. You will see that the smaller image remains unchanged, but the larger one becomes smaller to fit into the box.

你可以对容器内的图片做出其他选择。例如,你可能想要调整图片的大小,使其完全覆盖一个框。

¥You can make other choices about images inside containers. For example, you may want to size an image so it completely covers a box.

object-fit 属性可以为你提供帮助。使用 object-fit 时,可以通过多种方式调整替换元素的尺寸以适合盒子。

¥The object-fit property can help you here. When using object-fit the replaced element can be sized to fit a box in a variety of ways.

下面我们使用了值 cover,它缩小了图片的大小,保持纵横比,使其整齐地填充盒子。由于纵横比保持不变,图片的某些部分将被框裁剪掉。

¥Below we have used the value cover, which sizes the image down, maintaining the aspect ratio so that it neatly fills the box. As the aspect ratio is maintained, some parts of the image will be cropped by the box.

如果我们使用 contain 作为值,图片将被缩小,直到它足够小以适合框内。如果长宽比与盒子不同,这将导致 "letterboxing"。

¥If we use contain as a value, the image will be scaled down until it is small enough to fit inside the box. This will result in "letterboxing" if it is not the same aspect ratio as the box.

你还可以尝试使用 fill 的值,该值将填充该框但不保持纵横比。

¥You could also try the value of fill, which will fill the box but not maintain the aspect ratio.

替换布局中的元素

¥Replaced elements in layout

当在替换元素上使用各种 CSS 布局技术时,你可能会发现它们的行为与其他元素略有不同。例如,在网格布局中,元素默认被拉伸以填充其整个 网格区域。图片不拉伸;相反,它们与网格区域的开始对齐。

¥When using various CSS layout techniques on replaced elements, you may well find that they behave slightly differently from other elements. For example, in a grid layout, elements are stretched by default to fill their entire grid areas. Images do not stretch; instead, they are aligned to the start of their grid areas.

你可以在下面的示例中看到这种情况发生,其中我们有一个两列两行的网格容器,其中有四个项目。所有 <div> 元素都有背景颜色并拉伸以填充行和列。然而,图片不会拉伸。

¥You can see this happening in the example below where we have a two column, two row grid container, which has four items in it. All of the <div> elements have a background color and stretch to fill the row and column. The image, however, does not stretch.

如果你按顺序学习这些课程,那么你可能还没有看过布局。请记住,当替换元素成为网格或弹性布局的一部分时,它们具有不同的默认行为,本质上是为了避免它们被布局奇怪地拉伸。

¥If you are following these lessons in order then you may not have looked at layout yet. Just keep in mind that replaced elements, when they become part of a grid or flex layout, have different default behaviors, essentially to avoid them being stretched strangely by the layout.

要强制图片拉伸以填充其所在的网格单元,你必须执行如下操作:

¥To force the image to stretch to fill the grid cell it is in, you'd have to do something like the following:

css
img {
  width: 100%;
  height: 100%;
}

然而,这会拉伸图片,所以这可能不是你想要做的。

¥This would, however, stretch the image, so it's probably not what you'd want to do.

表单元素

¥Form elements

当涉及到 CSS 样式时,表单元素可能是一个棘手的问题。网络表单模块 包含有关这些样式的更棘手方面的详细指南,我不会在这里完全重现。然而,本节中有一些值得强调的关键基础知识。

¥Form elements can be a tricky issue when it comes to styling with CSS. The Web Forms module contains detailed guides to the trickier aspects of styling these, which I will not fully reproduce here. There are, however, a few key basics worth highlighting in this section.

许多表单控件通过 <input> 元素添加到你的页面 - 这定义了简单的表单字段(例如文本输入)到更复杂的字段(例如颜色和日期选择器)。还有一些附加元素,例如用于多行文本输入的 <textarea>,以及用于包含和标记表单部分的元素,例如 <fieldset><legend>

¥Many form controls are added to your page by way of the <input> element — this defines simple form fields such as text inputs, through to more complex fields such as color and date pickers. There are some additional elements, such as <textarea> for multiline text input, and also elements used to contain and label parts of forms such as <fieldset> and <legend>.

HTML 还包含一些属性,使 Web 开发者能够指示需要哪些字段,甚至需要输入的内容类型。如果用户输入意外内容或将必填字段留空,浏览器可能会显示错误消息。不同的浏览器允许此类项目的样式和自定义程度各不相同。

¥HTML also contains attributes that enable web developers to indicate which fields are required, and even the type of content that needs to be entered. If the user enters something unexpected, or leaves a required field blank, the browser can show an error message. Different browsers vary with one another in how much styling and customization they allow for such items.

设置文本输入元素的样式

¥Styling text input elements

允许文本输入的元素(例如 <input type="text">、更具体的 <input type="email"><textarea> 元素)非常容易设计样式,并且其行为往往与页面上的其他框一样。但是,这些元素的默认样式会有所不同,具体取决于用户访问网站所使用的操作系统和浏览器。

¥Elements that allow for text input, such as <input type="text">, and the more specific <input type="email">, and the <textarea> element are quite easy to style and tend to behave just like other boxes on your page. The default styling of these elements will differ, however, based on the operating system and browser that your user visits the site with.

在下面的示例中,我们使用 CSS 设置了一些文本输入的样式 - 你可以看到边框、边距和填充等内容均按你的预期应用。我们使用属性选择器来定位不同的输入类型。尝试通过调整边框、向字段添加背景颜色以及更改字体和填充来更改此表单的外观。

¥In the example below we have styled some text inputs using CSS — you can see that things such as borders, margins and padding all apply as you would expect. We are using attribute selectors to target the different input types. Try changing how this form looks by adjusting the borders, adding background colors to the fields, and changing fonts and padding.

警告:更改表单元素的样式时应小心,以确保用户仍然清楚它们是表单元素。你可以创建一个没有边框和背景的表单输入,它与周围的内容几乎无法区分,但这将使其很难识别和填写。

¥Warning: You should take care when changing the styling of form elements to make sure it is still obvious to the user they are form elements. You could create a form input with no borders and background that is almost indistinguishable from the content around it, but this would make it very hard to recognize and fill in.

正如 设计网页表单 课程中所解释的,许多更复杂的输入类型是由操作系统呈现的,并且无法设置样式。因此,你应该始终假设表单对于不同的访问者来说看起来会完全不同,并在多个浏览器中测试复杂的表单。

¥As explained in the lessons on styling web forms, many of the more complex input types are rendered by the operating system and are inaccessible to styling. You should, therefore, always assume that forms are going to look quite different for different visitors and test complex forms in a number of browsers.

继承和表单元素

¥Inheritance and form elements

在某些浏览器中,表单元素默认不继承字体样式。因此,如果你想确保表单字段使用正文或父元素上定义的字体,则应将此规则添加到 CSS 中。

¥In some browsers, form elements do not inherit font styling by default. Therefore, if you want to be sure that your form fields use the font defined on the body, or on a parent element, you should add this rule to your CSS.

css
button,
input,
select,
textarea {
  font-family: inherit;
  font-size: 100%;
}

表单元素和框大小

¥Form elements and box-sizing

在浏览器中,表单元素对不同的小部件使用不同的框大小规则。你在 我们的盒子模型课 中了解了 box-sizing 属性,你可以在设计表单样式时使用这些知识,以确保在表单元素上设置宽度和高度时获得一致的体验。

¥Across browsers, form elements use different box sizing rules for different widgets. You learned about the box-sizing property in our box model lesson and you can use this knowledge when styling forms to ensure a consistent experience when setting widths and heights on form elements.

为了保持一致性,最好将所有元素的边距和填充设置为 0,然后在设置特定控件的样式时将它们添加回来:

¥For consistency, it is a good idea to set margins and padding to 0 on all elements, then add these back in when styling particular controls:

css
button,
input,
select,
textarea {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

其他有用的设置

¥Other useful settings

除了上面提到的规则外,还应该在 <textarea> 上设置 overflow: auto,以在不需要滚动条时停止 IE 显示滚动条:

¥In addition to the rules mentioned above, you should also set overflow: auto on <textarea>s to stop IE showing a scrollbar when there is no need for one:

css
textarea {
  overflow: auto;
}

将所有内容整合到 "reset" 中

¥Putting it all together into a "reset"

作为最后一步,我们可以将上面讨论的各种属性封装到下面的 "表单重置" 中,以提供一致的工作基础。这包括最后三节中提到的所有项目:

¥As a final step, we can wrap up the various properties discussed above into the following "form reset" to provide a consistent base to work from. This includes all the items mentioned in the last three sections:

css
button,
input,
select,
textarea {
  font-family: inherit;
  font-size: 100%;
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

textarea {
  overflow: auto;
}

注意:许多开发者使用规范化样式表来创建一组用于所有项目的基线样式。通常,它们会执行与上述类似的操作,确保在你对 CSS 进行自己的工作之前,将跨浏览器的任何不同内容设置为一致的默认值。它们不再像以前那么重要,因为浏览器通常比过去更加一致。但是,如果你想看一个示例,请查看 Normalize.css,这是一种非常流行的样式表,被许多项目用作基础。

¥Note: Normalizing stylesheets are used by many developers to create a set of baseline styles to use on all projects. Typically these do similar things to those described above, making sure that anything different across browsers is set to a consistent default before you do your own work on the CSS. They are not as important as they once were, as browsers are typically more consistent than in the past. However if you want to take a look at one example, check out Normalize.css, which is a very popular stylesheet used as a base by many projects.

有关样式表单的更多信息,请查看这些指南的 HTML 部分中的两篇文章。

¥For further information on styling forms, take a look at the two articles in the HTML section of these guides.

测试你的技能!

¥Test your skills!

你已读完本文,但你还记得最重要的信息吗?在继续之前,你可以找到一些进一步的测试来验证你是否已保留此信息 - 请参阅 测试你的技能:图片和表单元素

¥You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Images and form elements.

概括

¥Summary

本课程重点介绍了在 CSS 中处理图片、媒体和其他不常见元素时会遇到的一些差异。

¥This lesson has highlighted some of the differences you will encounter when working with images, media, and other unusual elements in CSS.

在下一篇文章中,我们将学习如何 HTML 表格样式

¥In the next article, we'll learn how to style HTML tables.