- object-fit
- Try it
- Syntax
- Values
- Formal definition
- Formal syntax
- Examples
- Setting object-fit for an image
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- fit-content()
- Try it
- Syntax
- Values
- Examples
- Sizing grid columns with fit-content
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- css.properties.grid-template-columns.fit-content
- css.properties.width.fit-content_function
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- fit-content
- Syntax
- Examples
- Using fit-content for box sizing
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Fit-content и fit-content()
- Quick Chromia
- fit-content
- CSS The object-fit Property
- The CSS object-fit Property
- Example
- Using object-fit: cover;
- Example
- Using object-fit: contain;
- Example
- Using object-fit: fill;
- Example
- Using object-fit: none;
- Example
- Using object-fit: scale-down;
- Example
- Another Example
- Example
- Example
- CSS object-fit More Examples
- Example
- CSS Object-* Properties
object-fit
The object-fit CSS property sets how the content of a replaced element, such as an or , should be resized to fit its container.
You can alter the alignment of the replaced element’s content object within the element’s box using the object-position property.
Try it
Syntax
object-fit: contain; object-fit: cover; object-fit: fill; object-fit: none; object-fit: scale-down; /* Global values */ object-fit: inherit; object-fit: initial; object-fit: revert; object-fit: revert-layer; object-fit: unset;
The object-fit property is specified as a single keyword chosen from the list of values below.
Values
The replaced content is scaled to maintain its aspect ratio while fitting within the element’s content box. The entire object is made to fill the box, while preserving its aspect ratio, so the object will be «letterboxed» if its aspect ratio does not match the aspect ratio of the box.
The replaced content is sized to maintain its aspect ratio while filling the element’s entire content box. If the object’s aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit.
The replaced content is sized to fill the element’s content box. The entire object will completely fill the box. If the object’s aspect ratio does not match the aspect ratio of its box, then the object will be stretched to fit.
The replaced content is not resized.
The content is sized as if none or contain were specified, whichever would result in a smaller concrete object size.
Formal definition
Formal syntax
object-fit =
fill |
contain |
cover |
none |
scale-down
Examples
Setting object-fit for an image
HTML
section> h2>object-fit: fillh2> img class="fill" src="mdn_logo_only_color.png" alt="MDN Logo" /> img class="fill narrow" src="mdn_logo_only_color.png" alt="MDN Logo" /> h2>object-fit: containh2> img class="contain" src="mdn_logo_only_color.png" alt="MDN Logo" /> img class="contain narrow" src="mdn_logo_only_color.png" alt="MDN Logo" /> h2>object-fit: coverh2> img class="cover" src="mdn_logo_only_color.png" alt="MDN Logo" /> img class="cover narrow" src="mdn_logo_only_color.png" alt="MDN Logo" /> h2>object-fit: noneh2> img class="none" src="mdn_logo_only_color.png" alt="MDN Logo" /> img class="none narrow" src="mdn_logo_only_color.png" alt="MDN Logo" /> h2>object-fit: scale-downh2> img class="scale-down" src="mdn_logo_only_color.png" alt="MDN Logo" /> img class="scale-down narrow" src="mdn_logo_only_color.png" alt="MDN Logo" /> section>
CSS
h2 font-family: Courier New, monospace; font-size: 1em; margin: 1em 0 0.3em; > img width: 150px; height: 100px; border: 1px solid #000; margin: 10px 0; > .narrow width: 100px; height: 150px; > .fill object-fit: fill; > .contain object-fit: contain; > .cover object-fit: cover; > .none object-fit: none; > .scale-down object-fit: scale-down; >
Result
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 7, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
fit-content()
Baseline is determined by this web feature being supported on the current and the previous major versions of major browsers.
The fit-content() CSS function clamps a given size to an available size according to the formula min(maximum size, max(minimum size, argument)) .
Try it
The function can be used as a track size in CSS Grid properties, where the maximum size is defined by max-content and the minimum size by auto , which is calculated similar to auto (i.e., minmax(auto, max-content) ), except that the track size is clamped at argument if it is greater than the auto minimum.
See the grid-template-columns page for more information on the max-content and auto keywords.
The fit-content() function can also be used as laid out box size for width , height , min-width , min-height , max-width and max-height , where the maximum and minimum sizes refer to the content size.
Syntax
The fit-content() function accepts a or a as an argument.
/* values */ fit-content(200px) fit-content(5cm) fit-content(30vw) fit-content(100ch) /* value */ fit-content(40%)
Values
A percentage relative to the available space in the given axis.
In grid properties it is relative to the inline size of the grid container in column tracks and to the block size of the grid container for row tracks. Otherwise it is relative to the available inline size or block size of the laid out box depending on the writing mode.
Examples
Sizing grid columns with fit-content
HTML
div id="container"> div>Item as wide as the content.div> div> Item with more text in it. Because the contents of it are wider than the maximum width, it is clamped at 300 pixels. div> div>Flexible itemdiv> div>
CSS
#container display: grid; grid-template-columns: fit-content(300px) fit-content(300px) 1fr; grid-gap: 5px; box-sizing: border-box; height: 200px; width: 100%; background-color: #8cffa0; padding: 10px; > #container > div background-color: #8ca0ff; padding: 5px; >
Result
Specifications
Browser compatibility
css.properties.grid-template-columns.fit-content
BCD tables only load in the browser
css.properties.width.fit-content_function
BCD tables only load in the browser
See also
- Related sizing keywords: min-content , max-content
- Related CSS Grid properties: grid-template , grid-template-rows , grid-template-columns , grid-template-areas , grid-auto-columns , grid-auto-rows , grid-auto-flow
- Grid Layout Guide: Line-based placement with CSS Grid
- Grid Layout Guide: Grid template areas — Grid definition shorthands
Found a content problem with this page?
This page was last modified on Jul 17, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
fit-content
The fit-content behaves as fit-content(stretch) . In practice this means that the box will use the available space, but never more than max-content .
When used as laid out box size for width , height , min-width , min-height , max-width and max-height the maximum and minimum sizes refer to the content size.
Note: The CSS Sizing specification also defines the fit-content() function. This page details the keyword.
Syntax
width: fit-content; block-size: fit-content;
Examples
Using fit-content for box sizing
HTML
div class="container"> div class="item">Itemdiv> div class="item">Item with more text in it.div> div class="item"> Item with more text in it, hopefully we have added enough text so the text will start to wrap. div> div>
CSS
.container border: 2px solid #ccc; padding: 10px; width: 20em; > .item width: fit-content; background-color: #8ca0ff; padding: 5px; margin-bottom: 1em; >
Result
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 18, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Fit-content и fit-content()
Прежде чем приступить к рассмотрению fit-content, мы должны кратко рассмотреть два особых значения для width: min-content и max-content. Они нужны вам для понимания fit-content.
Обычно (то есть со значением width:auto) блок занимает столько места по горизонтали, сколько может. Вы можете изменить горизонтальное пространство, указав для width конкретное значение, но вы также можете указать браузеру определить его значение по содержимому поля. Вот что делают min-content и max-content:
min-content означает: минимальная ширина контейнера с содержимым. На практике это означает, что браузеры видят, какой элемент контента самый широкий, и устанавливают для ширины поля это значение. Самый широкий фрагмент контента — это самое длинное слово в тексте, самое широкое изображение, видео или другой объект.
Онлайн курс по JavaScript
Научитесь создавать приложения со сложными интерфейсами
Это основной язык для современной веб-разработки — почти 100% сайтов работает на JavaScript. Освойте его с нуля всего за 4 месяца, и вы сможете зарабатывать от 70 000 рублей.
max-content означает: максимальная ширина контейнера с содержимым . В случае текста это означает, что весь текст помещается в одну строку, а поле становится настолько широким, насколько это необходимо, чтобы вместить всю строку. В общем, это нежелательный эффект. Самым большим элементом контента также может быть изображением или видео; в этом случае браузеры используют эту ширину для определения ширины поля.
Если вы используете hyphens:auto или что-то подобное, браузер будет разбивать слова в правильных точках переноса, прежде чем определять минимальную ширину.
Quick Chromia
Все браузеры на базе Chromium на Android (протестированные в Chrome (v90), Samsung Internet (v87) и Edge (v77)) прерывают текст width:max-content в приведенном выше примере на тире и, таким образом, принимают ‘width: max-‘ в качестве максимального содержимого, при условии, что страница НЕ имеет мета-области просмотра. Ни один другой браузер не делает этого, в том числе Chrome на Mac.
Кроме того, Chromia на Android делает размер шрифта немного меньше, когда вы изменяете размер полей ниже максимально возможной ширины.
Этих ошибок НЕ возникает в UC (на основе Chromium 78). Кажется, UC принимает здесь свои собственные решения и невосприимчив к подобным ошибкам.
fit-content
По сути, понимание fit-content состоит в следующем:
CSS The object-fit Property
The CSS object-fit property is used to specify how an or should be resized to fit its container.
The CSS object-fit Property
The CSS object-fit property is used to specify how an or should be resized to fit its container.
This property tells the content to fill the container in a variety of ways; such as «preserve that aspect ratio» or «stretch up and take up as much space as possible».
Look at the following image from Paris. This image is 400 pixels wide and 300 pixels high:
However, if we style the image above to be half its width (200 pixels) and same height (300 pixels), it will look like this:
Example
We see that the image is being squished to fit the container of 200×300 pixels (its original aspect ratio is destroyed).
Here is where the object-fit property comes in. The object-fit property can take one of the following values:
- fill — This is default. The image is resized to fill the given dimension. If necessary, the image will be stretched or squished to fit
- contain — The image keeps its aspect ratio, but is resized to fit within the given dimension
- cover — The image keeps its aspect ratio and fills the given dimension. The image will be clipped to fit
- none — The image is not resized
- scale-down — the image is scaled down to the smallest version of none or contain
Using object-fit: cover;
If we use object-fit: cover; the image keeps its aspect ratio and fills the given dimension. The image will be clipped to fit:
Example
Using object-fit: contain;
If we use object-fit: contain; the image keeps its aspect ratio, but is resized to fit within the given dimension:
Example
Using object-fit: fill;
If we use object-fit: fill; the image is resized to fill the given dimension. If necessary, the image will be stretched or squished to fit:
Example
Using object-fit: none;
If we use object-fit: none; the image is not resized:
Example
Using object-fit: scale-down;
If we use object-fit: scale-down; the image is scaled down to the smallest version of none or contain :
Example
Another Example
Here we have two images and we want them to fill the width of 50% of the browser window and 100% of the height.
In the following example we do NOT use object-fit , so when we resize the browser window, the aspect ratio of the images will be destroyed:
Example
In the next example, we use object-fit: cover; , so when we resize the browser window, the aspect ratio of the images is preserved:
Example
CSS object-fit More Examples
The following example demonstrates all the possible values of the object-fit property in one example:
Example
CSS Object-* Properties
The following table lists the CSS object-* properties:
Property | Description |
---|---|
object-fit | Specifies how an |
object-position | Specifies how an |