使用 CSS 创建具有响应式容器宽高比

CSSCSSBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将学习如何使用 CSS 创建具有指定宽高比的响应式容器。你将了解 --aspect-ratio 自定义属性,以及如何使用 calc() 函数来计算容器的高度。你还将学习如何使用 object-fit: cover 属性设置子元素以保持宽高比。在本实验结束时,你将更好地理解如何在网页上创建视觉上吸引人的响应式容器。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL css(("`CSS`")) -.-> css/BasicConceptsGroup(["`Basic Concepts`"]) css(("`CSS`")) -.-> css/CoreLayoutGroup(["`Core Layout`"]) css(("`CSS`")) -.-> css/CSSPreprocessorsGroup(["`CSS Preprocessors`"]) css/BasicConceptsGroup -.-> css/selectors("`Selectors`") css/CoreLayoutGroup -.-> css/width_and_height("`Width and Height`") css/CoreLayoutGroup -.-> css/positioning("`Positioning`") css/CSSPreprocessorsGroup -.-> css/variables("`Variables`") css/CSSPreprocessorsGroup -.-> css/nesting("`Nesting`") subgraph Lab Skills css/selectors -.-> lab-35169{{"`使用 CSS 创建具有响应式容器宽高比`"}} css/width_and_height -.-> lab-35169{{"`使用 CSS 创建具有响应式容器宽高比`"}} css/positioning -.-> lab-35169{{"`使用 CSS 创建具有响应式容器宽高比`"}} css/variables -.-> lab-35169{{"`使用 CSS 创建具有响应式容器宽高比`"}} css/nesting -.-> lab-35169{{"`使用 CSS 创建具有响应式容器宽高比`"}} end

宽高比

虚拟机中已经提供了 index.htmlstyle.css

这段代码使用 CSS 自定义属性和 calc() 函数创建了一个具有特定宽高比的响应式容器。按照以下步骤来实现:

  1. 使用 CSS 自定义属性 --aspect-ratio 定义所需的宽高比。
  2. 将容器元素的 position 属性设置为 relativeheight 属性设置为 0
  3. 使用 calc() 函数和 --aspect-ratio 自定义属性计算容器元素的高度,并将其设置为 padding-bottom 属性。
  4. 将容器元素的直接子元素设置为 position: absolutetop: 0left: 0width: 100%height: 100%
  5. 通过将子元素的 object-fit 属性设置为 cover 来保持其宽高比。

使用以下 HTML 和 CSS 代码创建容器:

<div class="container">
  <img src="https://picsum.photos/id/119/800/450" />
</div>
.container {
  --aspect-ratio: 16/9;
  position: relative;
  height: 0;
  padding-bottom: calc(100% / var(--aspect-ratio));
}

.container > * {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

请点击右下角的“Go Live”在端口 8080 上运行网络服务。然后,你可以刷新“Web 8080”标签页来预览网页。

总结

恭喜你!你已经完成了宽高比实验。你可以在 LabEx 中练习更多实验来提升你的技能。

您可能感兴趣的其他 CSS 教程