search
HomeWeb Front-endHTML Tutorial[CSS3] Using CSS’s object-fit and object-position Properties(译)_html/css_WEB-ITnose

原文地址: https://www.sitepoint.com/using-css-object-fit-object-position-properties/

标题:Using CSS’s object-fit and object-position Properties – 使用 CSS 的 object-fit和 object-position属性

视频和图像资源用在网站的时候可能存在定位的问题。

比如说你已经在CSS中明确的指定了图片的宽度。如果宽度是以百分比或者单位比指定的,并且高度是设为自适应 auto,那么调整浏览器窗口的大小会保持图片的宽高比。

但是,有时候你只有有限的空间并且需要给图片的高度设置约束条件。那么改变浏览器的窗口大小肯定会影响图片的宽高比。

和图片尺寸及宽高比相关的很多问题,包括刚才讨论的问题,都可以用 CSS 中的 object-fit和 object-position属性解决。

这些属性和更广为人知的 background-size以及 background-position属性很相似。所以即使你以前从来没听过它们,你在接下来了解它们如何工作的过程中也不会遇到很多问题。

这两个属性都用于替换元素。但是为了简化内容,在这篇文章中我将用图片代替替换元素。

为什么使用 object-fit和 object-position

你可能会疑惑为什么在可以使用 background-size和 background-position的情况下还要要用这两个属性呢?事实上,至少有两个很好的理由。

首先,考虑这样一个场景。你有一个图像资源,而它是文章的一部分。如果像前文的描述那样在 CSS 中设定图片的尺寸,那么重新改变浏览器的窗口大小会导致图片的宽高比混乱。在这样一个情况下,你会倾向于通过 div使用 background-size和 background-position属性,因为简单的 img标签不会起到任何作用。

另一个原因是因为背景属性不能应用于视频元素而 object-fit和 object-position属性可以。因此,需要展示视频元素的时候, object-fit和 object-postion是你唯一的选择。

关于 objcet-fit属性

这个属性决定了像图像和视屏一样的替换内容如何在容器中布局。它有五个可能的值:

  • fill
  • contain
  • cover
  • none
  • scale-down

它们的用法如下:

.fit-image {  object-fit: fill|contain|cover|none|scale-down;} 

当使用 fill值得时候,图片会完全填充容器。在下面的例子中图片的高度会完全适应盒子的高度。这也是 object-fit的默认值。

See the Pen Object Fit: Fillby SitePoint ( @SitePoint) on CodePen.

contain值通过这样一种方式来调整图片,在使图片适配容器的时候依然保持原来的宽高比。这是为了达到两个目的。它在保持图片不超出容器的同时避免了图像失真。如果图像没有完全填充容器,它会用默认的背景色填充空白部分。

See the Pen Object Fit: Containby SitePoint ( @SitePoint) on CodePen.

当你不知道图片的尺寸但是又希望能把图片装进一个已知宽度的容器的时候,你可以使用 contain值。

如果你希望图片完全填充容器同时保持它的宽高比,你应该使用 cover属性。在下面的例子中,图像会进行缩放从而使得最小的部分会完美贴合容器大小,而溢出容器的部分则会被裁剪。

See the Pen Object Fit: Coverby SitePoint ( @SitePoint) on CodePen.

为了展示图像的原始尺寸并且忽略容器设置好的的尺寸值,你应该使用 none。在下面的例子中图像没有被重新调整大小。但是,如果图像的任何部分超出了容器之外,那些部分会被裁剪掉。

See the Pen Object Fit: Noneby SitePoint ( @SitePoint) on CodePen.

最后的一个 object-fit值是 scale-down。顾名思义,它会缩小图片。这意味着它会根据图像分别被设置为 none或者 contain后,取其中最小的值作为他的调整后尺寸。换句话说,如果在我们的图像中没有尺寸比容器中各自的尺寸要大,那么 none就会生效。

See the Pen Object Fit: scale-downby SitePoint ( @SitePoint) on CodePen.

object-position属性

正如我们前面看到的一样, cover属性会在保持图像原来宽高比的情况下填充容器。而图片也会默认居中显示。在焦点是中心点的情况下这很好理解。但如果焦点并不是中心点呢?

此时 objcet-position属性就可以帮到你。它的工作原理和 background-position一样。下面这段代码就把图像的对齐位置设为左上方。

.zero-zero {  object-position: 0px 0px;} 

你可以通过使用百分比来指定图片的位置而不仅仅是像素。例如, object-position:0% 0%就是左上角而 object-position: 100% 100%就是右下角。使用百分比在你不知道图片的尺寸时很有用。

当图像的宽高比和你的容器很相似的时候,设置 object-position并不会带来什么变化。但是,但宽高比不一样的时候这会带来很好地结果。下面的代码可以证明我的观点。

See the Pen GZewMJby SitePoint ( @SitePoint) on CodePen.

在第二个案例中通过设置 position 为 top-left,使得太阳重新变回焦点。

还有一件事值得一提, object-position属性可以做成动画效果,如果使用得当也能产生让人眼前一亮的效果。下面是一段例子:

img {  /* other CSS here... */  object-fit: cover;  object-position: 0% 0%;  animation: ltr 5s alternateinfinite;}   @keyframes ltr {  0% {    object-position: 0% 0%;  }  25% {    object-position: 20% 0%;  }  100% {    object-position: 100% 100%;  }} 

在这段代码中,我把图像的位置作为关键帧动画,正如你所看,最后的效果看起来也不错。

See the Pen Animating the object-position Propertyby SitePoint ( @SitePoint) on CodePen.

这也可以当成视频效果使用,想象从一个人移动到另一个人的情况。

浏览器支持和 Polyfills

虽然这些属性非常有用,但你能否使用它们还依赖于 浏览器的支持。 object-fit除了 IE/Edge 外被所有主流浏览器支持,而 object-position除了 IE/Edge 和 Safari 外被所有主流浏览器支持。

一般来说,你可能只需要 object-fit属性。如果你愿意牺牲一部分用户的体验你可以使用该属性。如果你需要支持古老的浏览器,你可以使用 Federico Brigante 开发的 polyfill。

结论

我希望你能够希望这个教程以及附带的例子。如果我遗漏了什么或者有你想要补充的,请通过留言让我知道。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Role of HTML: Structuring Web ContentThe Role of HTML: Structuring Web ContentApr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTML and Code: A Closer Look at the TerminologyHTML and Code: A Closer Look at the TerminologyApr 10, 2025 am 09:28 AM

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

HTML, CSS, and JavaScript: Essential Tools for Web DevelopersHTML, CSS, and JavaScript: Essential Tools for Web DevelopersApr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

The Roles of HTML, CSS, and JavaScript: Core ResponsibilitiesThe Roles of HTML, CSS, and JavaScript: Core ResponsibilitiesApr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools