Width

CSS Учебник

CSS СТАРТCSS ВведениеCSS СинтаксисCSS СелекторыCSS Как подключитьCSS ЦветаCSS background-colorCSS borderCSS marginCSS paddingCSS height/widthCSS Блочная модельCSS КонтурCSS ТекстCSS ШрифтыCSS ИконкиCSS СсылкиCSS СпискиCSS ТаблицыCSS displayCSS max-widthCSS positionCSS overflowCSS float/clearCSS inline-blockCSS ВыравниваниеCSS КомбинаторыCSS Псевдо-классыCSS Псевдо-элементыCSS opacity/transparencyCSS Панель навигацииCSS Выпадающие спискиCSS Галерея изображенийCSS Спрайты изображенийCSS Селекторы атрибутовCSS ФормыCSS СчётчикиCSS Макет веб-сайтаCSS ЕдиницыCSS Специфичности

CSS Tutorial

CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors Colors RGB HEX HSL

CSS Backgrounds Background Color Background Image Background Repeat Background Attachment Background Shorthand

CSS Borders Borders Border Width Border Color Border Sides Border Shorthand Rounded Borders

CSS Margins Margins Margin Collapse

CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline Outline Outline Width Outline Color Outline Shorthand Outline Offset

CSS Text Text Color Text Alignment Text Decoration Text Transformation Text Spacing Text Shadow

CSS Fonts Font Family Font Style Font Size Font Google Font Shorthand

CSS IconsCSS LinksCSS ListsCSS TablesCSS DisplayCSS Max-widthCSS PositionCSS OverflowCSS Float Float Clear Float Examples

CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar Navbar Vertical Navbar Horizontal Navbar

CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS Specificity


浏览器兼容性

Update compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
Chrome Full support 1 Edge Full support 12 Firefox Full support 1 IE Full support 4 Opera Full support 3.5 Safari Full support 1 WebView Android Full support 1 Chrome Android Full support 18 Firefox Android Full support 4 Opera Android Full support 10.1 Safari iOS Full support 1 Samsung Internet Android Full support 1.0
Animatable Chrome Full support 26 Edge Full support 12 Firefox Full support 16 IE Full support 11 Opera Full support 15 Safari Full support 6.1 WebView Android Full support 4.4 Chrome Android Full support 26 Firefox Android Full support 16 Opera Android Full support 14 Safari iOS Full support 6.1 Samsung Internet Android Full support 1.5

ExperimentalNon-standard

Chrome Full support 46 Edge Full support 79 Firefox No support No IE No support No Opera Full support 33 Safari Full support 12 WebView Android Full support 46 Chrome Android Full support 46 Firefox Android No support No Opera Android Full support 33 Safari iOS Full support 12 Samsung Internet Android Full support 5.0
Chrome Full support 46 Edge Full support 79 Firefox Full support 3 Prefixed IE No support No Opera Full support 33 Safari Full support 11 WebView Android Full support 46 Chrome Android Full support 46 Firefox Android Full support 4 Prefixed Opera Android Full support 33 Safari iOS Full support 11 Samsung Internet Android Full support 5.0
Chrome Full support 46 Edge Full support 79 Firefox Full support 66 IE No support No Opera Full support 44 Safari Full support 11 WebView Android Full support 46 Chrome Android Full support 46 Firefox Android Full support 66 Opera Android Full support 43 Safari iOS Full support 11 Samsung Internet Android Full support 5.0
Chrome Full support 46 Edge Full support 79 Firefox Full support 66 IE No support No Opera Full support 33 Safari Full support 11 WebView Android Full support 46 Chrome Android Full support 46 Firefox Android Full support 66 Opera Android Full support 33 Safari iOS Full support 11 Samsung Internet Android Full support 5.0
Experimental Chrome Full support 22 Alternate Name Edge Full support 79 Alternate Name Firefox Full support 3 Alternate Name IE No support No Opera Full support 15 Alternate Name Safari Full support 6.1 Alternate Name WebView Android Full support 4.4 Alternate Name Chrome Android Full support 25 Alternate Name Firefox Android Full support 4 Alternate Name Opera Android Full support 14 Alternate Name Safari iOS Full support 6.1 Alternate Name Samsung Internet Android Full support 5.0 Alternate Name

The compatibility table on this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

The CSS object-fit Property

The CSS property is used to specify how an <img> or <video> 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, which is 400×300 pixels:

However, if we style the image above to be 200×400 pixels, it will look like this:

img {  width: 200px;  height: 400px;}

We see that the image is being squeezed to fit the container of 200×400 pixels, and its original aspect ratio is destroyed.

If we use it will cut off the sides of the image, preserving the aspect ratio, and also filling in the space, like this:

示例

p.goldie {
  background: gold;
}
<p class="goldie">The Mozilla community produces a lot of great software.</p>

像素 px 和字高 em

.px_length {
  width: 200px;
  background-color: red;
  color: white;
  border: 1px solid black;
}

.em_length {
  width: 20em;
  background-color: white;
  color: red;
  border: 1px solid black;
}
<div class="px_length">以 px 度量的宽度</div>
<div class="em_length">以 em 度量的宽度</div>

百分比

.percent {
  width: 20%;
  background-color: silver;
  border: 1px solid red;
}
<div class="percent">按照百分比度量的宽度</div>
p.maxgreen {
  background: lightgreen;
  width: intrinsic;           /* Safari/WebKit 使用了非标准的名称 */
  width: -moz-max-content;    /* Firefox/Gecko */
  width: -webkit-max-content; /* Chrome */
}
<p class="maxgreen">The Mozilla community produces a lot of great software.</p>
p.minblue {
  background: lightblue;
  width: -moz-min-content;    /* Firefox */
  width: -webkit-min-content; /* Chrome */
}
<p class="minblue">The Mozilla community produces a lot of great software.</p>

浏览器兼容性

Update compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
Chrome Full support 1 Edge Full support 12 Firefox Full support 1 IE Full support 4 Opera Full support 7 Safari Full support 1 WebView Android Full support 1 Chrome Android Full support 18 Firefox Android Full support 4 Opera Android Full support 10.1 Safari iOS Full support 1 Samsung Internet Android Full support 1.0
Chrome Full support 46 Edge Full support 79 Firefox No support No IE No support No Opera Full support 33 Safari Full support 11 WebView Android Full support 46 Chrome Android Full support 46 Firefox Android No support No Opera Android Full support 33 Safari iOS Full support 11 Samsung Internet Android Full support 5.0
Chrome Full support 46 Edge Full support 79 Firefox Full support 66 IE No support No Opera Full support 44 Safari Full support 11 WebView Android Full support 46 Chrome Android Full support 46 Firefox Android Full support 66 Opera Android Full support 43 Safari iOS Full support 11 Samsung Internet Android Full support 5.0
Chrome Full support 46 Edge Full support 79 Firefox Full support 66 IE No support No Opera Full support 44 Safari Full support 11 WebView Android Full support 46 Chrome Android Full support 46 Firefox Android Full support 66 Opera Android Full support 43 Safari iOS Full support 11 Samsung Internet Android Full support 5.0
Chrome Full support 28 Alternate Name Edge Full support 79 Alternate Name Firefox No support No IE No support No Opera Full support 15 Alternate Name Safari Full support 9 Alternate Name WebView Android Full support 4.4 Alternate Name Chrome Android Full support 28 Alternate Name Firefox Android No support No Opera Android Full support 15 Alternate Name Safari iOS Full support 9 Alternate Name Samsung Internet Android Full support 5.0 Alternate Name

Примеры

p.goldie {
  background: gold;
}
<p class="goldie">Сообщество Mozilla производит множество отличного ПО.</p>

Пиксели и em

.px_length {
  width: 200px;
  background-color: red;
  color: white;
  border: 1px solid black;
}

.em_length {
  width: 20em;
  background-color: white;
  color: red;
  border: 1px solid black;
}
<div class="px_length">Ширина в пикселях</div>
<div class="em_length">Ширина в em</div>

Проценты

.percent {
  width: 20%;
  background-color: silver;
  border: 1px solid red;
}
<div class="percent">Ширина в процентах</div>

max-content

p.maxgreen {
  background: lightgreen;
  width: intrinsic;           /* Safari/WebKit используют нестандартное имя */
  width: -moz-max-content;    /* Firefox/Gecko */
  width: -webkit-max-content; /* Chrome */
}
<p class="maxgreen">Сообщество Mozilla производит множество отличного ПО.</p>

min-content

p.minblue {
  background: lightblue;
  width: -moz-min-content;    /* Firefox */
  width: -webkit-min-content; /* Chrome */
}
<p class="minblue">Сообщество Mozilla производит множество отличного ПО.</p>

规范

Specification Status Comment
Working Draft Added the , , , , , keywords.
Working Draft Lists  as animatable.
Recommendation Adds support for the values and precises on which element it applies to.
Recommendation Initial definition.
Working Draft Adds new sizing keywords for width and height.
初始值
适用元素 all elements but non-replaced inline elements, table columns, and column groups
是否是继承属性
Percentages The percentage is calculated with respect to the height of the generated box’s containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to . A percentage height on the root element is relative to the initial containing block.
计算值 a percentage or or the absolute length
Animation type a , or calc();

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities

CSS Properties

align-content align-items align-self all animation animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animation-name animation-play-state animation-timing-function

backface-visibility background background-attachment background-blend-mode background-clip background-color background-image background-origin background-position background-repeat background-size border border-bottom border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-collapse border-color border-image border-image-outset border-image-repeat border-image-slice border-image-source border-image-width border-left border-left-color border-left-style border-left-width border-radius border-right border-right-color border-right-style border-right-width border-spacing border-style border-top border-top-color border-top-left-radius border-top-right-radius border-top-style border-top-width border-width bottom box-decoration-break box-shadow box-sizing break-after break-before break-inside

caption-side caret-color @charset clear clip clip-path color column-count column-fill column-gap column-rule column-rule-color column-rule-style column-rule-width column-span column-width columns content counter-increment counter-reset cursor

direction display empty-cells filter flex flex-basis flex-direction flex-flow flex-grow flex-shrink flex-wrap float font @font-face font-family font-feature-settings font-kerning font-size font-size-adjust font-stretch font-style font-variant font-variant-caps font-weight

grid grid-area grid-auto-columns grid-auto-flow grid-auto-rows grid-column grid-column-end grid-column-gap grid-column-start grid-gap grid-row grid-row-end grid-row-gap grid-row-start grid-template grid-template-areas grid-template-columns grid-template-rows

hanging-punctuation height hyphens @import isolation justify-content @keyframes left letter-spacing

line-height list-style list-style-image list-style-position list-style-type

margin margin-bottom margin-left margin-right margin-top max-height max-width @media min-height min-width mix-blend-mode

object-fit object-position opacity order outline outline-color outline-offset outline-style outline-width overflow overflow-x overflow-y

padding padding-bottom padding-left padding-right padding-top page-break-after page-break-before page-break-inside perspective perspective-origin pointer-events position quotes

resize right


scroll-behavior

tab-size table-layout text-align text-align-last text-decoration text-decoration-color text-decoration-line text-decoration-style text-indent text-justify text-overflow text-shadow text-transform top

transform transform-origin transform-style transition transition-delay transition-duration transition-property transition-timing-function

unicode-bidi user-select

vertical-align visibility

white-space width word-break word-spacing word-wrap writing-mode

z-index

All Values of The CSS object-fit Property

The property can have the following values:

  • — This is default. The replaced content is sized to fill the element’s content box. If necessary, the object will be stretched or squished to fit
  • — The replaced content is scaled to maintain its aspect ratio while fitting within the element’s content box
  • — The replaced content is sized to maintain its aspect ratio while filling the element’s entire content box. The object will be clipped to fit
  • — The replaced content is not resized
  • — The content is sized as if none or contain were specified (would result in a smaller concrete object size)

The following example demonstrates all the possible values of the property:

Example

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

Спецификации

Спецификация Статус Комментарий
Рабочий черновик Добавляет ключевые слова , , , и . (CSS3 Box и CSS3 Writing Modes черновики, используемые для определения этих ключевых слов, были заменены этой спецификацией)
Кандидат в рекомендации Добавляет ключевое слово  и использует его как первоначальное значение.
Рабочий черновик Определяет  как анимируемое.
Рекомендация Первоначальное определение.
Начальное значение
Применяется к все элементы, кроме незаменяемых строчных элементов, табличных колонок и групп колонок
Наследуется нет
Проценты Процент для генерируемого блока рассчитывается по отношению к высоте содержащего блока. Если высота содержащего блока не задана явно (т.е. зависит от высоты содержимого), и этот этот элемент позиционирован не абсолютно, процентное значение интерпретируется как .
Обработка значения процент, как указан, или аблосютная длина
Animation type

Usage

Initialization:

<style>.container{width25em;height25em;}.media{width100%;height100%;object-fitcover;}</style><divclass="container"><imgalt=""src="https://unsplash.it/800/600/"class="media"data-object-fit="cover" /></div><scriptsrc="dist/objectFitPolyfill.min.js"><script>

Customized object-fit/object-position:

<divclass="container"><imgalt=""src="https://unsplash.it/800/600/"class="media"data-object-fit="contain"data-object-position="top left" /></div><divclass="container"><imgalt=""src="https://unsplash.it/800/600/"class="media"data-object-fit="none"data-object-position="25% 75%" /></div><divclass="container"><imgalt=""src="https://unsplash.it/800/600/"class="media"data-object-fit="scale-down"data-object-position="3em -1em" /></div>

If you’re only interested in using the basic polyfill (which assumes and ), you can save yourself some bytes by using:

<divclass="container"><imgalt=""src="https://unsplash.it/800/600/"class="media"data-object-fit /></div><scriptsrc="dist/objectFitPolyfill.basic.min.js"><script>

Синтаксис

/* <length> значения */
min-height: 3.5em;

/* <percentage> значения */
min-height: 10%;

/* Значения-ключевые слова */
min-height: max-content;
min-height: min-content;
min-height: fit-content;
min-height: fill-available;

/* Глобальные значения */
min-height: inherit;
min-height: initial;
min-height: unset;

Значения

Минимальная высота выражается как от высоты родительского блока. Отрицательные значения делают свойство недействительным.

Значения-ключевые слова

Минимальная высота для flex-элементов по умолчанию, предоставляет более разумное значение по умолчанию, чем 0 для других способов разметки.

Внутренняя предпочтительная высота.

Внутренняя минимальная высота.

Высота родительского блока минус вертикальные , , и

(Обратите внимание, что некоторые браузеры реализуют устаревшее имя для этого ключевого слова., .)

Согласно CSS3 Box, это синоним . CSS3 Sizing определяет более сложный алгоритм, но ни один браузер не реализует его даже экспериментальным путем.

The Webstandard

Normally, the image would be stretched to the specified dimensions but due to the usage of the CSS property the image now is scaled proportionally, until every pixel of the defined area is covered by parts of it. In the case of cover this means that parts of the image will overlap the given area.

The following are the possible values and their implications:

  • streches the image exactly to the defined dimensions which results in a distorted image. Comparable to . That’s the default value.
  • leaves the image at its natural size and centers it inside within the defined area. If the image’s natural dimensions are larger than the defined area parts of the image will poke out of it unless you also set on it. Comparable to .
  • scales the image up or down until all of it fits into the defined area. This mode respects the image’s natural aspect-ratio. It’s also called «letterbox view». Comparable to .
  • scales the image up or down until every pixel of the defined area is covered with parts of the image. Sort of «pan and scan view». This means that parts of the image will poke out of the defined area unless you also set on it. This mode respects the image’s natural aspect-ratio. Comparable to .

Примечание

Во многих случаях, вы можете захотеть установить ширину элемента, а после этого добавить какие-то внутренние отступы к элементу и будете думать что ширина элемента установленная в свойстве будет сохранена. В обычном случае (который, по умолчанию), это не сработает потому что как и говорилось ранее свойство используется для настройки ширины области содержимого элемента. Любые добавленные внутренние отступы к элементу будут добавлены к его окончательной ширине.

Чтобы избежать этого и сохранить ширину элемента после добавление любого количества отступов, можно использовать свойство border-box со значением .

Когда на элементе установлено  ширина указанная с помощью свойства также будет включать любые отступы добавленные к нему. 


Ключевые слова (в отличии от значений с единицами измерений и процентами) не зависят от свойства border-box, они всегда устанавливают размер области содержимого.

Отрицательные значения ширины не допустимы.

Property Values

Value Description Try it
fill This is default. The replaced content is sized to fill the element’s content box. If necessary, the object will be stretched or squished to fit Try it »
contain The replaced content is scaled to maintain its aspect ratio while fitting within the element’s content box Try it »
cover The replaced content is sized to maintain its aspect ratio while filling the element’s entire content box. The object will be clipped to fit Try it »
none The replaced content is not resized Try it »
scale-down The content is sized as if none or contain were specified (would result in a smaller concrete object size) Try it »
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

浏览器兼容性

We’re converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven’t yet converted the data it contains.

  • Desktop
  • Mobile
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 1.0 1.0 (1.7 or earlier) 7.0 4.0 2.0.2 (416), buggy before
applies to 未实现 (Yes) 未实现 (Yes) 未实现
, , , and 未实现 3.0 (1.9) 未实现 未实现 未实现
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support ? ? ? ? ?

CSS 2.1 explicitly leaves the behavior of with undefined. Therefore any behavior is CSS2.1-compliant; newer CSS specifications may define this behavior, so Web developers shouldn’t rely on a specific one now.

Gecko experimentally implements the definitions given in CSS3 Basic Box. This one defines and not . Also the definition of is simpler than in CSS3 Sizing.

WebKit implements an earlier proposal for setting the height to an intrinsic height: the keywords , instead of , and , instead of There is no equivalent for or .


С этим читают