- CSS backgrounds and borders
- Backgrounds, borders, and box shadows in action
- Reference
- Properties
- Data types
- Guides
- Related concepts
- Specifications
- See also
- Found a content problem with this page?
- Resizing background images with background-size
- Tiling a large image
- HTML
- CSS
- Result
- Stretching an image
- Scaling an image up
- Special values: «contain» and «cover»
- contain
- HTML
- CSS
- Result
- cover
- HTML
- CSS
- Result
- See also
- Found a content problem with this page?
- Свойство background-size
- Синтаксис
- Ключевые слова
- Использование
- Пример
- Пример
- Пример
- Пример
- Пример
- Пример . Значение contain
- Пример . Значение cover
- Пример . Улучшим работу cover
- Пример . Значения в пикселях и процентах
- Пример . Значение auto для одной из сторон + проценты
- Пример . Значение auto для одной из сторон + пиксели
- Пример . Значение 100% для обеих сторон
- Пример . Значение contain
- Пример . Значение cover
- Смотрите также
CSS backgrounds and borders
The CSS backgrounds and borders module provides properties for adding borders, rounded corners, and box shadows to elements.
You can add different types of border styles, including borders made of images of any image type, from raster images to CSS gradients. Borders can be square or rounded, and a different radius can be set for each corner. Elements can be rounded whether or not they have a visible border.
Box shadows include inset and outset shadow, single or multiple shadows, and solid or allowed to fade to transparent. An outer box-shadow casts a shadow as if the border-box of the element were opaque. An inner box-shadow casts a shadow as if everything outside the padding edge were opaque. The shadow can be solid or include a spread distance with the shadow color transitioning to transparent.
The properties in this module also let you define whether cells inside a should have shared or separate borders.
Backgrounds, borders, and box shadows in action
This sample of borders, backgrounds, and box shadows consists of centered background images made of linear and radial gradients. A series of box shadows make the border appear to «pop». The element on the left has a border image set. The element on the right has a rounded dotted border.
The background images are defined with background-image . The images are centered with background-position . Different values of the background-clip property for the multiple background images are used to make the background images stay within the content box. The background color gets clipped to the padding box preventing the background from appearing through the transparent sections for the border-image and the dotted border . The rounded corners in the element on the right are created using the border-radius property. A single box-shadow declaration is used to set all the shadows, both inset and outset.
To see the code for this sample, view the source on GitHub.
Reference
Properties
- background-attachment
- background-clip
- background-color
- background-image
- background-origin
- background-position
- background-repeat
- background-size
- background shorthand
- background-position-x Experimental
- background-position-y Experimental
- background-position-inline Experimental
- background-position-block Experimental
- border-bottom-color
- border-bottom-style
- border-bottom-width
- border-bottom shorthand
- border-left-color
- border-left-style
- border-left-width
- border-left shorthand
- border-right-color
- border-right-style
- border-right-width
- border-right shorthand
- border-top-color
- border-top-style
- border-top-width
- border-top shorthand
- border-color shorthand
- border-style shorthand
- border-width shorthand
- border shorthand
- border-collapse
- border-bottom-left-radius
- border-bottom-right-radius
- border-top-left-radius
- border-top-right-radius
- border-radius shorthand
- border-image-outset
- border-image-repeat
- border-image-slice
- border-image-source
- border-image-width
- border-image shorthand
- box-shadow
Data types
Guides
Explains how to implement decorative images using CSS background images.
Explains how to set one or more backgrounds on an element.
Describes how to change the size and repeating behavior of background images.
Explains how borders, along with other box model properties, impact the CSS box model.
Explains how to create CSS gradient background images.
Related concepts
- border-block-end-color property
- border-block-start-color property
- border-inline-end-color property
- border-inline-start-color property
- border-block-end-style property
- border-block-start-style property
- border-inline-end-style property
- border-inline-start-style property
- border-block-end-width property
- border-block-start-width property
- border-inline-end-width property
- border-inline-start-width property
- border-start-start-radius property
- border-start-end-radius property
- border-end-start-radius property
- border-end-end-radius property
- box-sizing property
- box-decoration-break property
- text-shadow property
- url() CSS function
- data type
- data type
- data type
- currentcolor keyword
Specifications
See also
- Interactive tools that let you visually create borders images, rounded corners, and box shadows:
- Border-image generator
- Border-radius generator
- Box-shadow generator
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.
Resizing background images with background-size
The background-size CSS property lets you resize the background image of an element, overriding the default behavior of tiling the image at its full size by specifying the width and/or height of the image. By doing so, you can scale the image upward or downward as desired.
Tiling a large image
Let’s consider a large image, a 2982×2808 Firefox logo image. We want (for some reason likely involving horrifyingly bad site design) to tile four copies of this image into a 300×300-pixel element. To do this, we can use a fixed background-size value of 150 pixels.
HTML
div class="tiledBackground">div>
CSS
.tiledBackground background-image: url(https://www.mozilla.org/media/img/logos/firefox/logo-quantum.9c5e96634f92.png); background-size: 150px; width: 300px; height: 300px; border: 2px solid; color: pink; >
Result
Stretching an image
You can also specify both the horizontal and vertical sizes of the image, like this:
background-size: 300px 150px;
The result looks like this:
Scaling an image up
On the other end of the spectrum, you can scale an image up in the background. Here we scale a 32×32 pixel favicon to 300×300 pixels:
.square2 background-image: url(favicon.png); background-size: 300px; width: 300px; height: 300px; border: 2px solid; text-shadow: white 0px 0px 2px; font-size: 16px; >
As you can see, the CSS is actually essentially identical, save the name of the image file.
Special values: «contain» and «cover»
Besides values, the background-size CSS property offers two special size values, contain and cover . Let’s take a look at these.
contain
The contain value specifies that, regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container. Try resizing the example below to see this in action.
HTML
div class="bgSizeContain"> p>Try resizing this element!p> div>
CSS
.bgSizeContain background-image: url(https://www.mozilla.org/media/img/logos/firefox/logo-quantum.9c5e96634f92.png); background-size: contain; width: 160px; height: 160px; border: 2px solid; color: pink; resize: both; overflow: scroll; >
Result
cover
The cover value specifies that the background image should be sized so that it is as small as possible while ensuring that both dimensions are greater than or equal to the corresponding size of the container. Try resizing the example below to see this in action.
HTML
div class="bgSizeCover"> p>Try resizing this element!p> div>
CSS
.bgSizeCover background-image: url(https://www.mozilla.org/media/img/logos/firefox/logo-quantum.9c5e96634f92.png); background-size: cover; width: 160px; height: 160px; border: 2px solid; color: pink; resize: both; overflow: scroll; >
Result
See also
Found a content problem with this page?
This page was last modified on May 24, 2023 by MDN contributors.
Your blueprint for a better internet.
Свойство background-size
Свойство background-size задает размер картинки фона. Значением свойства служат любые единицы для размеров, либо ключевые слова auto, cover или contain.
Синтаксис
Ключевые слова
Значение Описание auto Фон будет иметь натуральный размер, такой, как реальный размер картинки фона. Если же auto задано только для одной стороны, то по этой стороне фон будет масштабироваться так, чтобы иметь неискаженные пропорции. cover Масштабирует картинку так, чтобы она накрыла собой весь блок с сохранением пропорций. Картинка будет стараться поместиться целиком, но это не всегда будет получаться, поэтому какая-то ее часть будет обрезаться. Блок всегда будет покрыт картинкой целиком. contain Масштабирует картинку так, чтобы она целиком влезла в блок с сохранением пропорций. При этом она может занять или всю ширину, или всю высоту (зависит от пропорций картинки и от размеров элемента). Блок в общем случае будет покрыт картинкой не целиком (зато картинка всегда будет видна вся, хоть и в уменьшенном варианте). Значение по умолчанию: auto .
Использование
Единицы для размеров и auto могут быть использованы в различных комбинациях, например, так: auto 20px , или 30% 20px , или auto 30% и так далее. В этом случае первый параметр задает размер фона по ширине, а второй параметр — размер фона по высоте. Если указан один параметр — то он будет задавать размер фона и по ширине, и по высоте одновременно.
Пример
Сейчас фоновая картинка будет иметь свой натуральный размер:
Пример
Сейчас фоновая картинка будет размер 300px на 400px (в нашем случае пропорции картинки исказятся):
Пример
Сейчас фоновая картинка будет размер 400px на 400px (в нашем случае пропорции картинки исказятся):
Пример
Сейчас фоновая картинка будет размер 400px по горизонтали, а по вертикали ее размер подстроится так, чтобы пропорции не исказились:
Пример
Сейчас фоновая картинка будет размер 400px по вертикали, а по горизонтали ее размер подстроится так, чтобы пропорции не исказились:
Пример . Значение contain
Посмотрите на работу значения contain :
Пример . Значение cover
Посмотрите на работу значения cover :
Пример . Улучшим работу cover
Работу значения cover можно улучшить, если отцентрировать картинку с помощью свойства background-position (в нашем случае на видимые части начнут попадать головы лошадей, а не их задницы):
В данном примере фоновая картинка занимает 50% ширины и 30% высоты окна браузера (при этом картинка будет иметь искаженные пропорции):
Пример . Значения в пикселях и процентах
В данном примере фоновая картинка занимает 50% ширины окна браузера и 400px по высоте (при этом картинка будет иметь искаженные пропорции):
Пример . Значение auto для одной из сторон + проценты
В данном примере фоновая картинка занимает 50% ширины окна браузера, а по высоте подстроится так, чтобы сохранить пропорции (поуменьшайте окно браузера, чтобы убедиться, что этой действительно так — картинка будут оставаться неискаженной):
Пример . Значение auto для одной из сторон + пиксели
В данном примере фоновая картинка занимает 300px по высоте, а по ширине подстроится так, чтобы сохранить пропорции:
Пример . Значение 100% для обеих сторон
Сейчас картинка будет всегда на весь экран с искаженными пропорциями (так как и по ширине и по высоте мы берем 100% , можно было просто написать одно значение):
Пример . Значение contain
Сейчас картинка будет занимать всю ширину или всю высоту с сохранением пропорций. Поуменьшайте окно браузера, чтобы увидеть, что картинка в различных состояниях будет занимать или всю ширину или всю высоту:
Пример . Значение cover
Сейчас картинка будет целиком накрывать собой в блок с сохранением пропорций: Картинка будет стараться поместиться целиком, но это не всегда будет получаться, поэтому какая-то ее часть будет обрезаться:
Сравните с тем, как будет выглядеть картинка по умолчанию (при значении auto). Поуменьшайте окно браузера, чтобы увидеть отличия:
Смотрите также