Как изменить размер фонового изображения css

Значение background-size в CSS позволяет задавать размер фонового изображения. Изображение может быть оставлено в исходном размере, растянуто, или подогнано под размеры доступного пространства.

Описание

Значение background-size в CSS позволяет задавать размер фонового изображения. Изображение может быть оставлено в исходном размере, растянуто, или подогнано под размеры доступного пространства.

Примечание: Предупреждение: Если значение этого свойства не задано в сокращённом свойстве background, которое применяется к элементу после CSS-свойства background-size, то значение этого свойства затем сбрасывается до исходного значения c помощью сокращённого свойства.

Начальное значение auto auto
Применяется к все элементы. Это также применяется к ::first-letter и ::first-line.
Наследуется нет
Проценты относительно области позиционирования фона
Обработка значения как указано, но с относительной длиной, конвертируемой в абсолютные длины
Animation type repeatable list of simple list of length, percentage, or calc

Синтаксис

/* Ключевые слова */
background-size: cover;
background-size: contain;

/* Указано одно значение - ширина изображения, */
/* высота в таком случае устанавливается в auto */
background-size: 50%;
background-size: 3em;
background-size: 12px;
background-size: auto;

/* Указаны два значения - */
/* ширина и высота соответственно */
background-size: 50% auto;
background-size: 3em 25%;
background-size: auto 6px;
background-size: auto auto;

/* Значения для нескольких фонов */
/* Не путайте такую запись с background-size: auto auto */
background-size: auto, auto;
background-size: 50%, 25%, 25%;
background-size: 6px, auto, contain;

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

Значения

<размер>

Значение <length> позволяет масштабировать размер фонового изображения в заданном измерении. Отрицательный размер не допускается.

<проценты>

Значение <percentage>, которое масштабирует фоновое изображение в соответствующем измерении до указанного процента области расположения фона, которое определяется значением background-origin. Область расположения фона по умолчанию является областью, содержащей содержимое поля и его отступы; область также может быть изменена на содержимое или область, содержащую границы, отступы и содержимое. Если attachment фона является fixed, область позиционирования фона вместо этого является всей областью окна браузера, не включая область, покрытую полосами прокрутки, если они присутствуют. Отрицательные проценты не допускаются.

auto

Значение позволяет изменять размер фонового изображения в соответствии с заданным направлением, сохраняя его пропорции.

contain

Масштабирует картинку так, чтобы она максимально накрыла собой весь блок. Картинка при этом не обрезается, а вписывается в блок с сохранением пропорций.

cover

Ключевое слово, обратное contain. Масштабирует изображение как можно больше c сохранением пропорций изображения (изображение не становится сплющенным). Когда изображение и контейнер имеют разные размеры, изображение обрезается либо влево / вправо, либо сверху / снизу.

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

Примечание: Предупреждение: Это поведение изменилось в Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5). До этого, градиенты обрабатывались как изображения без внутренних размеров, с внутренней пропорцией, идентичной пропорции области расположения фона.

Фоновые изображения, сгенерированные из элементов с использованием -moz-element (en-US) (которые фактически соответствуют элементу) в настоящее время обрабатываются как изображения с размерами элемента, или как область расположения фона, если элементом является SVG, с соответствующей внутренней пропорцией.

Примечание: Предупреждение: Это не определённое в настоящее время поведение, которое заключается в том, что внутренние размеры и пропорция должны быть такими же как у элемента во всех случаях.

Визуализированный размер фонового изображения затем вычисляется следующим способом:

Если оба атрибута в background-size заданы и различны от auto:

Фоновое изображение отображается в указанном размере.

Если background-size содержит contain или cover:

Изображение визуализируется с сохранением его внутренней пропорции при наибольшем размере, который содержится внутри области размещения фона или покрывает её. Если изображение не имеет внутренней пропорции, оно отображается с размером области расположения фона.

Если background-size установлен как auto или auto auto:

Если изображение имеет оба внутренних размера, оно отображается с таким размером. Если оно не имеет внутренних размеров и внутренней пропорции, оно отображается с размером области расположения фона. Если оно не имеет размеров, но имеет пропорцию, оно отображается так, если был был бы указан contain. Если изображение имеет один внутренний размер и пропорцию, оно отображается с размером, определённым этим одним размером и пропорцией. Если изображение имеет один внутренний размер, но не имеет пропорцию, оно отображается с использованием внутреннего размера и соответствующим размером области позиционирования фона.

Если background-size содержит один атрибут auto и один не-auto:

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

Обратите внимание, что изменение размера фона для векторных изображений, в которых отсутствуют внутренние размеры или пропорции, ещё не полностью реализовано во всех браузерах. Будьте осторожны, полагаясь на поведение, описанное выше, и тестируйте в нескольких браузерах (в частности, включая версии Firefox 7 или более ранней версии и Firefox 8 или более поздней версии), чтобы убедиться, что различные визуализации приемлемы.

Формальный синтаксис

Примеры

Эта демонстрация background-size: cover и эта демонстрация background-size: contain предназначены для открытия в новых окнах, чтобы вы могли видеть, как contain и cover ведут себя, когда размеры области расположения фона изменяются. Эта серия демонстраций, как работает background-size и взаимодействует с другими свойствами background-*, должна в значительной степени охватить оставшуюся основу в том, как использовать background-size отдельно и в сочетании с другими свойствами.

Замечания

Если вы указываете градиент в качестве фона и указали background-size, который будет использоваться вместе с ним, лучше не указывать размер, который использует единственную автоматическую составную часть, или задаётся с использованием только значения ширины (для примера, background-size: 50%). Рендеринг градиентов в таких случаях изменился в Firefox 8, и в настоящее время он обычно несовместим во всех браузерах, которые не реализуют рендеринг в соответствии с CSS3 спецификацией background-size и с CSS3 спецификацией градиента значений изображения.

.bar {
       width: 50px; height: 100px;
       background-image: gradient(...);

       /* Лучше не использовать */
       background-size: 25px;
       background-size: 50%;
       background-size: auto 50px;
       background-size: auto 50%;

       /* Допускается */
       background-size: 25px 50px;
       background-size: 50% 50%;
}

Обратите внимание, что особенно не рекомендуется использовать размер в пикселях и размер auto с градиентом, потому что невозможно воспроизвести рендеринг в версиях Firefox до 8 и в браузерах, не реализующих рендеринг Firefox 8, без знания точного размера элемента, фон которого указывается.

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

Specification
CSS Backgrounds and Borders Module Level 3
# the-background-size

Совместимость с браузерами

BCD tables only load in the browser

Смотрите также

Оригинал: sitepoint.com/css3-background-size-property

Перевод: Влад Мержевич

В CSS 2.1 фоновая картинка, применяемая к контейнеру, сохраняет свои фиксированные размеры. К счастью, в CSS3 введено свойство background-size, с помощью которого фон может быть растянут или сжат. Оно идеально подходит, если вы создаёте шаблон для адаптивного веб-дизайна.

Есть несколько способов определения размеров — взгляните на демонстрационную страницу background-size.

Абсолютное изменение размера

Могут применяться единицы измерения.

background-size: ширина высота;

По умолчанию ширина и высота установлена как auto, что оставляет исходные размеры изображения.

Вы можете задать новый размер изображения с помощью абсолютных единиц измерения, таких как px, em, cm и др. Пропорции изменятся, если это необходимо. Например, если наша фоновая картинка имеет размеры 200×200 пикселов, то следующий код оставит эту высоту, но сделает ширину в два раза меньше:

background-size: 100px 200px;

Если указано только одно значение, оно считается шириной. Высота устанавливается как auto и сохраняются пропорции:

background-size: 100px;
  /* аналогично */
background-size: 100px auto;

Данный код масштабирует изображение с 200×200 до 100×100 пикселов.

Относительное изменение размера через проценты

Если применяются проценты, размеры основываются на элементе, а НЕ изображении:

background-size: 50% auto;

Ширина фонового изображения, таким образом, зависит от размеров контейнера. Если у контейнера ширина 500px, то размер нашего изображения уменьшится до 250×250.

Использование процентов может быть полезно для адаптивного дизайна. Поменяйте ширину демонстрационной страницы чтобы понять, как изменяются размеры.

Масштабирование до максимального размера

Свойство background-size также понимает ключевое слово contain. Оно масштабирует изображение таким образом, чтобы оно заполняло контейнер. Другими словами, изображение будет увеличиваться или уменьшаться пропорционально, но ширина и высота не будут превышать размеры контейнера:

background-size: contain;

Заполнение фоном

Свойство background-size также понимает ключевое слово cover. Изображение будет масштабироваться так, чтобы заполнить весь контейнер, но если различаются соотношения сторон, то картинка будет обрезана.

background-size: cover;

Масштабирование нескольких фонов

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

background:
  url("sheep.png") 60% 90% no-repeat,
  url("sheep.png") 40% 50% no-repeat,
  url("sheep.png") 10% 20% no-repeat #393;
  background-size: 240px 210px, auto, 150px;

Работа в браузерах

Последние версии всех браузеров поддерживают background-size без префиксов.

IE8 и ниже не поддерживают это свойство. Вы можете использовать фильтр IE для эмуляции значений content и cover, но невозможно изменить размер фоновой картинки без помощи уловок, вроде добавления настоящей картинки позади других элементов. Это грязно, так что я рекомендую изящную деградацию.

Просмотр демонстрационной страницы с background-size.

Размер фонового изображения может быть изменен и масштабирован. В CSS2.1 фоновые изображения, применяемые к контейнеру, сохраняют свои фиксированные размеры. К счастью CSS3 ввел свойство background-size, которое позволяет растянуть или сжать фон. Оно идеально подходит, если вы используете методы адаптивного веб-дизайна для создания шаблонов.

Здесь можете найти разные методы:

Когда мы устанавливаем фоновое изображение, ширина и высота изображения по умолчанию устанавливаются в «auto», которое сохраняет оригинальный размер изображения. А если необходимо изменить размер изображения, могут быть использованы абсолютные измерения для установления нового размера (px, em, cm и др).

Измерения высоты могут быть применены, используя свойство background-size с абсолютным измерением.

При изменении размеров изображения пропорции (видимая область и форма отображения) должны быть сохранены. В противном случае, изображение может искажаться и терять качество.

Давайте рассмотрим пример фонового изображения с измененным размером:

Пример

<!DOCTYPE html>
<html>
  <head>
    <title>Фоновое изображение с измененным размером</title>
    <style>
      .resized {
      width: 400px;
      height: 300px;
      background-image: url("/uploads/media/default/0001/01/b408569013c0bb32b2afb0f0d45e93e982347951.jpeg");
      background-size: 300px 200px;
      background-repeat: no-repeat;
      border: 1px solid #999;
      }
    </style>
  </head>
  <body>
    <h2>Фоновое изображение с измененным размером</h2>
    <div class="resized"></div>
  </body>
</html>

Использование процентных значений может быть довольно полезным при адаптивном дизайне. Когда используется процентное значение, размеры основываются на элементе, а не изображении. Если свойство background-size установлено как «100% 100%», фоновое изображение будет растянуто таким образом, чтобы оно заполняло всю область контента.

Пример

<!DOCTYPE html>
<html>
  <head>
    <title>Фоновое изображение с измененным размером</title>
    <style>
      .resized {
      width: 100%;
      height: 400px;
      background-image: url("/uploads/media/default/0001/01/b408569013c0bb32b2afb0f0d45e93e982347951.jpeg");
      background-size: 100% 100%;
      background-repeat: no-repeat;
      border: 2px solid #999;
      }
    </style>
  </head>
  <body>
    <h2>Фоновое изображение с измененным размером</h2>
    <div class="resized"></div>
  </body>
</html>

Но ширина фонового изображения зависит от размера контейнера. Не рекомендуется использовать проценты, когда имейте определенную ширину для контейнера.

Когда свойство background-size установлено в значение «contain», фоновое изображение будет масштабировано таким образом, чтобы оно заполняло область контента. Но пропорции изображения (отношение высоты и ширины) будут сохранены.

Значение «contain» указывает, что фоновое изображение будет масштабировано независимо от размера контейнера таким образом, что каждая сторона была максимально больше, не переходя длину контейнера с соответствующей стороны.

Другими словами, изображение будет увеличиваться или уменьшаться пропорционально, но размеры контейнера не могут быть больше ширины и высоты.

Пример

<!DOCTYPE html>
<html>
  <head>
    <title>Адаптивное фоновое изображение с измененным размером</title>
    <style>
      .resized {
      width: 100%;
      height: 400px;
      background-image: url("/uploads/media/default/0001/01/b408569013c0bb32b2afb0f0d45e93e982347951.jpeg");
      background-repeat: no-repeat;
      background-size: contain;
      border: 1px solid #999;
      }
    </style>
  </head>
  <body>
    <h2>Адаптивное фоновое изображение с измененным размером</h2>
    <p>Измените размер браузера и увидите результат:</p>
    <div class="resized"></div>
  </body>
</html>

Когда свойство background-size установлено в значение «cover», фоновое изображение будет масштабировано таким образом, чтобы оно заполняло всю область контента. Изображение будет масштабировано, чтобы заполнить контентную область, но оно будет обрезано, если соотношения сторон различаются.

Пример

<!DOCTYPE html>
<html>
  <head>
    <title>Адаптивное фоновое изображение с измененным размером</title>
    <style>
      .resized {
      width: 100%;
      height: 400px;
      background-image: url("/uploads/media/default/0001/01/b408569013c0bb32b2afb0f0d45e93e982347951.jpeg");
      background-size: cover;
      border: 1px solid #999;
      }
    </style>
  </head>
  <body>
    <h2>Адаптивное фоновое изображение с измененным размером</h2>
    <p>Измените размер браузера и увидите результат:</p>
    <div class="resized"></div>
  </body>
</html>

Огромное фото на большом экране будет смотреться идеально, но на экране маленького устройства оно не будет таким эффектным. Тогда зачем загрузить большое фото, если вы все равно должны уменьшить его?

Можно использовать мультимедийные запросы для отображения разных изображений на разных устройствах.

Здесь используется правило @media. В данном примере можно увидеть одно большое изображение и другое поменьше. Они установлены так, чтобы быть отображены по-разному на разных устройствах. Вы увидите результат сами если измените ширину браузера.

Пример

<!DOCTYPE html>
<html>
  <head>
    <title>Адаптивное фоновое изображение с измененным размером</title>
    <style>
      /* For width smaller than 400px: */
      body {
      background-repeat: no-repeat;
      background-image: url("/uploads/media/default/0001/01/25acddb3da54207bc6beb5838f65f022feaa81d7.jpeg");
      }
      /* For width 400px and larger: */
      @media only screen and (min-width: 400px) {
      body { 
      background-image: url("/uploads/media/default/0001/03/6514e37cd15dbe1bca3e3b961baa3a19e2283dc3.jpeg"); 
      }
      }
    </style>
  </head>
  <body>
    <p style="margin-top:220px;">Измените ширину браузера, и фоновое изображение изменится при 400px.</p>
  </body>
</html>

CSS2

If you need to make the image bigger, you must edit the image itself in an image editor.

If you use the img tag, you can change the size, but that would not give you the desired result if you need the image to be background for some other content (and it will not repeat itself like you seems to want)…

CSS3 unleash the powers

This is possible to do in CSS3 with background-size.

All modern browsers support this, so unless you need to support old browsers, this is the way to do it.
Supported browsers:

Mozilla Firefox 4.0+ (Gecko 2.0+), Microsoft Internet Explorer 9.0+, Opera 10.0+, Safari 4.1+ (webkit 532) and Chrome 3.0+.

.stretch{
/* Will stretch to specified width/height */
  background-size: 200px 150px;
}
.stretch-content{
/* Will stretch to width/height of element */
  background-size: 100% 100%;
}

.resize-width{
/* width: 150px, height: auto to retain aspect ratio */
  background-size: 150px Auto;
}
.resize-height{
/* height: 150px, width: auto to retain aspect ratio */
  background-size: Auto 150px;
}
.resize-fill-and-clip{ 
  /* Resize to fill and retain aspect ratio.
     Will cause clipping if aspect ratio of box is different from image. */ 
  background-size: cover;
}
.resize-best-fit{
/* Resize to best fit and retain aspect ratio.
   Will cause gap if aspect ratio of box is different from image. */ 
  background-size: contain;
}

In particular, I like the cover and contain values that gives us new power of control that we didn’t have before.

Round

You can also use background-size: round that have a meaning in combination with repeat:

.resize-best-fit-in-repeat{
/* Resize to best fit in a whole number of times in x-direction */ 
  background-size: round auto; /* Height: auto is to keep aspect ratio */
  background-repeat: repeat;
}

This will adjust the image width so it fits a whole number of times in the background positioning area.


Additional note
If the size you need is static pixel size, it is still smart to physically resize the actual image. This is both to improve quality of the resize (given that your image software does a better job than the browsers), and to save bandwidth if the original image is larger than what to display.

I want that my background image stretch and scale depending on the browser viewport size.

I’ve seen some questions on Stack Overflow that do the job, like Stretch and scale CSS background for example. It works well, but I want to place the image using background, not with an img tag.

In that one an img tag is placed, and then with CSS we tribute to the img tag.

width:100%; height:100%;

It works, but that question is a bit old, and states that in CSS 3 resizing a background image will work pretty well. I’ve tried this example the first one, but it didn’t work out for me.

Is there a good method to do it with the background-image declaration?

Community's user avatar

asked Jul 19, 2009 at 15:51

Fábio Antunes's user avatar

Fábio AntunesFábio Antunes

16.8k17 gold badges73 silver badges96 bronze badges

4

CSS3 has a nice little attribute called background-size:cover.

This scales the image so that the background area is completely covered by the background image while maintaining the aspect ratio. The entire area will be covered. However, part of the image may not be visible if the width/height of the resized image is too large.

TiyebM's user avatar

TiyebM

2,6263 gold badges39 silver badges64 bronze badges

answered Sep 10, 2011 at 14:28

Vashishtha Jogi's user avatar

Vashishtha JogiVashishtha Jogi

12.1k2 gold badges19 silver badges20 bronze badges

7

You could use the CSS3 property to do it quite nicely. It resizes to ratio so no image distortion (although it does upscale small images). Just note, it’s not implemented in all browsers yet.

background-size: 100%;

answered Feb 28, 2011 at 0:44

Matt Burgess's user avatar

Matt BurgessMatt Burgess

5,0182 gold badges16 silver badges15 bronze badges

4

Using the code I mentioned…

HTML

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

CSS

#background {
    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1; /* Ensure div tag stays behind content; -999 might work, too. */
}

.stretch {
    width:100%;
    height:100%;
}

That produces the desired effect: only the content will scroll, not the background.

The background image resizes to the browser viewport for any screen size. When the content doesn’t fit the browser viewport, and the user needs to scroll the page, the background image remains fixed in the viewport while the content scrolls.

With CSS 3 it seems this would be a lot easier.

Community's user avatar

answered Jul 30, 2009 at 18:21

Fábio Antunes's user avatar

Fábio AntunesFábio Antunes

16.8k17 gold badges73 silver badges96 bronze badges

5

CSS:

html,body {
    background: url(images/bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover; /* For WebKit*/
    -moz-background-size: cover;    /* Mozilla*/
    -o-background-size: cover;      /* Opera*/
    background-size: cover;         /* Generic*/
}

Josh Crozier's user avatar

Josh Crozier

228k54 gold badges386 silver badges301 bronze badges

answered Mar 23, 2012 at 19:58

1

background-size: 100% 100%; 

stretches the background to fill the entire element on both axes.

Peter Mortensen's user avatar

answered Jan 26, 2016 at 18:34

yeahdixon's user avatar

yeahdixonyeahdixon

6,5671 gold badge40 silver badges43 bronze badges

0

The following CSS part should stretch the image with all browsers.

I do this dynamically for each page. Therefore I use PHP to generate its own HTML tag for each page. All the pictures are in the ‘image’ folder and end with ‘Bg.jpg’.

<html style="
      background: url(images/'.$pic.'Bg.jpg) no-repeat center center fixed;
      -webkit-background-size: cover;
      -moz-background-size: cover;
      -o-background-size: cover;
      background-size: cover;
      filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/'.$pic.'Bg.jpg',     sizingMethod='scale');
      -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/'.$pic.'Bg.jpg', sizingMethod='scale')
";>

If you have only one background picture for all pages then you may remove the $pic variable, remove escaping back-slashes, adjust paths and place this code in your CSS file.

html{
    background: url(images/homeBg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/homeBg.jpg',     sizingMethod='scale');
    -ms-filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/homeBg', sizingMethod='scale');
}

This was tested with Internet Explorer 9, Chrome 21, and Firefox 14.

Popnoodles's user avatar

Popnoodles

27.9k2 gold badges44 silver badges53 bronze badges

answered Aug 6, 2012 at 13:41

Thorsten Niehues's user avatar

Thorsten NiehuesThorsten Niehues

13.4k20 gold badges75 silver badges111 bronze badges

1

Use this CSS:

background: url('img.png') no-repeat; 
background-size: 100%;

answered May 9, 2011 at 9:41

Rory Harvey's user avatar

Rory HarveyRory Harvey

2,5392 gold badges21 silver badges27 bronze badges

0

You can actually achieve the same effect as a background image with the img tag. You just have to set its z-index lower than everything else, set position:absolute and use a transparent background for every box in the foreground.

answered Jul 19, 2009 at 17:14

Kim Stebel's user avatar

Kim StebelKim Stebel

41.6k12 gold badges125 silver badges142 bronze badges

4

You can add this class into your CSS file.

.stretch {
    background: url(images/bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

It works in:

  • Safari 3 or later
  • Chrome Whatever or later
  • Internet Explorer 9 or later
  • Opera 10 or later (Opera 9.5 supported background-size, but not the keywords)
  • Firefox 3.6 or later (Firefox 4 supports non-vendor prefixed version)

Peter Mortensen's user avatar

answered Apr 17, 2015 at 7:57

Arunraj S's user avatar

Arunraj SArunraj S

7487 silver badges25 bronze badges

1

In order to scale your images appropriately based on the container size, use the following:

background-size: contain;
background-repeat: no-repeat;

Roman Snitko's user avatar

answered Jan 7, 2017 at 18:52

justinpees's user avatar

justinpeesjustinpees

3824 silver badges20 bronze badges

I use this, and it works with all browsers:

<html>
    <head>
        <title>Stretched Background Image</title>
        <style type="text/css">
            /* Remove margins from the 'html' and 'body' tags, and ensure the page takes up full screen height. */
            html, body {height:100%; margin:0; padding:0;}

            /* Set the position and dimensions of the background image. */
            #page-background {position:fixed; top:0; left:0; width:100%; height:100%;}

            /* Specify the position and layering for the content that needs to appear in front of the background image. Must have a higher z-index value than the background image. Also add some padding to compensate for removing the margin from the 'html' and 'body' tags. */
            #content {position:relative; z-index:1; padding:10px;}
        </style>
        <!-- The above code doesn't work in Internet Explorer 6. To address this, we use a conditional comment to specify an alternative style sheet for IE 6. -->
        <!--[if IE 6]>
        <style type="text/css">
            html {overflow-y:hidden;}
            body {overflow-y:auto;}
            #page-background {position:absolute; z-index:-1;}
            #content {position:static;padding:10px;}
        </style>
        <![endif]-->
    </head>
    <body>
        <div id="page-background"><img src="http://www.quackit.com/pix/milford_sound/milford_sound.jpg" width="100%" height="100%" alt="Smile"></div>
        <div id="content">
            <h2>Stretch that Background Image!</h2>
            <p>This text appears in front of the background image. This is because we've used CSS to layer the content in front of the background image. The background image will stretch to fit your browser window. You can see the image grow and shrink as you resize your browser.</p>
            <p>Go on, try it - resize your browser!</p>
        </div>
    </body>
</html>

Peter Mortensen's user avatar

answered May 2, 2012 at 14:39

Mahdi jokar's user avatar

Mahdi jokarMahdi jokar

1,2576 gold badges30 silver badges50 bronze badges

I wanted to center and scale a background image, without stretching it to the entire page, and I wanted the aspect ratio to be maintained. This worked for me, thanks to the variations suggested in other answers:

INLINE IMAGE: ————————

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

CSS ———————————-

html {
    height:100%;
}

#background {
    text-align: center;
    width: 100%; 
    height: 100%; 
    position: fixed;
    left: 0px; 
    top: 0px; 
    z-index: -1;
}

.stretch {
    margin: auto;
    height:100%;
}

Peter Mortensen's user avatar

answered Dec 24, 2010 at 13:05

AnnieDee's user avatar

AnnieDeeAnnieDee

911 silver badge1 bronze badge

0

Thanks!

But then it was not working for the Google Chrome and Safari browsers (stretching worked, but the hight of the pictures was only 2 mm!), until someone told me what lacks:

Try to set height:auto;min-height:100%;

So change that for your height:100%; line, gives:

#### #background {
    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1;
}

.stretch {
    width:100%;
    height:auto;
    min-height:100%;
}

Just before that newly added code I have this in my Drupal Tendu themes style.css:

html, body{height:100%;}

#page{background:#ffffff; height:auto !important;height:100%;min-height:100%;position:relative;}

Then I have to make a new block within Drupal with the picture while adding class=stretch:

< img alt=»» class=»stretch» src=»pic.url» />

Just copying a picture with the editor in that Drupal block doesn’t work; one has to change the editor to non-formatted text.

Peter Mortensen's user avatar

answered Apr 4, 2010 at 16:47

Cybr's user avatar

CybrCybr

811 silver badge1 bronze badge

I agree with the image in absolute div with 100% width and height. Make sure you set 100% width and height for the body in the CSS and set margins and padding to zero. Another issue you will find with this method is that when selecting text, the selection area can sometimes encompass the background image, which has the unfortunate effect of making the full page have the selected state. You can get round this by using the user-select:none CSS rule, like so:

<html>
    <head>
        <style type="text/css">

            html,body {
                height: 100%;
                width: 100%
                margin: none;
                padding: none;
            }

            #background {
                width: 100%;
                height: 100%;
                position: fixed;
                left: 0px;
                top: 0px;
                z-index: -99999;
                -webkit-user-select: none;
                -khtml-user-select: none;
                -moz-user-select: none;
                -o-user-select: none;
                user-select: none;
            }

            #background img {
                width: 100%;
                height: 100%;
            }

            #main{ z-index:10;}
        </style>
    </head>
    <body>
        <div id="main">
            content here
        </div>
        <div id="background"><img src="bg.jpg"></div>
    </body>
</html>

Again, Internet Explorer is the bad guy here, because it doesn’t recognise the user-select option — not even Internet Explorer 10 preview supports it, so you have the option of either using JavaScript to prevent background image selection (for example, http://www.felgall.com/jstip35.htm ) or using CSS 3 background-stretch method.

Also, for SEO I would put the background image at the bottom of the page, but if the background image takes too long to load (that is, with a white background initially), you could move to the top of the page.

Peter Mortensen's user avatar

answered Jul 6, 2011 at 10:38

Myke Black's user avatar

Myke BlackMyke Black

1,29915 silver badges15 bronze badges

1

I used a combination of the background-X CSS properties to achieve the ideal scaling background image.

background-size: cover;
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;

This makes the background always cover the entire browser window and remains centered when scaling.

Peter Mortensen's user avatar

answered Nov 12, 2018 at 4:02

Ryan Den-Kaat's user avatar

Use the Backstretch plugin. One could even have several images slide. It also works within containers. This way for example one could have only a portion of the background been covered with an background image.

Since even I could get it to work proves it to be an easy to use plugin :).

Peter Mortensen's user avatar

answered Sep 9, 2013 at 23:49

Daniel's user avatar

The following worked for me.

.back-ground {
   background-image: url("../assets/background.png");
   background-size: 100vw 100vh;
}

that worked to cover the entire background on different dimensions

answered Mar 25, 2020 at 21:07

tony2tones's user avatar

tony2tonestony2tones

1,2841 gold badge14 silver badges18 bronze badges

1

If you want to have the content centered horizontally, use a combination like this:

background-repeat: no-repeat;
background-size: cover;
background-position: center;

This will look beautiful.

Peter Mortensen's user avatar

answered Jan 29, 2019 at 22:12

Samuel Ramzan's user avatar

Samuel RamzanSamuel Ramzan

1,7141 gold badge15 silver badges24 bronze badges

Use this CSS:

background-size: 100% 100%

answered Nov 19, 2018 at 12:29

Shady Mohamed Sherif's user avatar

1

You can use the border-image : yourimage property to scale the image up to the border. Even if you give the background-image, the border image will be drawn over it.

The border-image property is very useful if your style sheet is implemented somewhere which doesn’t support CSS 3. If you are using Google Chrome or Firefox, then I recommend the background-size:cover property itself.

Peter Mortensen's user avatar

answered Jul 2, 2017 at 13:51

Natesh bhat's user avatar

Natesh bhatNatesh bhat

11.8k10 gold badges81 silver badges116 bronze badges

Do you want to achieve this just using one image? Because you can actually make somewhat similar to a stretching background using two images. PNG images for instance.

I’ve done this before, and it’s not that hard. Besides, I think stretching would just harm the quality of the background. And if you add a huge image it would slow down slow computers and browsers.

Peter Mortensen's user avatar

answered Jul 19, 2009 at 16:08

MarioRicalde's user avatar

MarioRicaldeMarioRicalde

8,9336 gold badges39 silver badges42 bronze badges

3

I want that my background image stretch and scale depending on the browser viewport size.

I’ve seen some questions on Stack Overflow that do the job, like Stretch and scale CSS background for example. It works well, but I want to place the image using background, not with an img tag.

In that one an img tag is placed, and then with CSS we tribute to the img tag.

width:100%; height:100%;

It works, but that question is a bit old, and states that in CSS 3 resizing a background image will work pretty well. I’ve tried this example the first one, but it didn’t work out for me.

Is there a good method to do it with the background-image declaration?

Community's user avatar

asked Jul 19, 2009 at 15:51

Fábio Antunes's user avatar

Fábio AntunesFábio Antunes

16.8k17 gold badges73 silver badges96 bronze badges

4

CSS3 has a nice little attribute called background-size:cover.

This scales the image so that the background area is completely covered by the background image while maintaining the aspect ratio. The entire area will be covered. However, part of the image may not be visible if the width/height of the resized image is too large.

TiyebM's user avatar

TiyebM

2,6263 gold badges39 silver badges64 bronze badges

answered Sep 10, 2011 at 14:28

Vashishtha Jogi's user avatar

Vashishtha JogiVashishtha Jogi

12.1k2 gold badges19 silver badges20 bronze badges

7

You could use the CSS3 property to do it quite nicely. It resizes to ratio so no image distortion (although it does upscale small images). Just note, it’s not implemented in all browsers yet.

background-size: 100%;

answered Feb 28, 2011 at 0:44

Matt Burgess's user avatar

Matt BurgessMatt Burgess

5,0182 gold badges16 silver badges15 bronze badges

4

Using the code I mentioned…

HTML

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

CSS

#background {
    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1; /* Ensure div tag stays behind content; -999 might work, too. */
}

.stretch {
    width:100%;
    height:100%;
}

That produces the desired effect: only the content will scroll, not the background.

The background image resizes to the browser viewport for any screen size. When the content doesn’t fit the browser viewport, and the user needs to scroll the page, the background image remains fixed in the viewport while the content scrolls.

With CSS 3 it seems this would be a lot easier.

Community's user avatar

answered Jul 30, 2009 at 18:21

Fábio Antunes's user avatar

Fábio AntunesFábio Antunes

16.8k17 gold badges73 silver badges96 bronze badges

5

CSS:

html,body {
    background: url(images/bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover; /* For WebKit*/
    -moz-background-size: cover;    /* Mozilla*/
    -o-background-size: cover;      /* Opera*/
    background-size: cover;         /* Generic*/
}

Josh Crozier's user avatar

Josh Crozier

228k54 gold badges386 silver badges301 bronze badges

answered Mar 23, 2012 at 19:58

1

background-size: 100% 100%; 

stretches the background to fill the entire element on both axes.

Peter Mortensen's user avatar

answered Jan 26, 2016 at 18:34

yeahdixon's user avatar

yeahdixonyeahdixon

6,5671 gold badge40 silver badges43 bronze badges

0

The following CSS part should stretch the image with all browsers.

I do this dynamically for each page. Therefore I use PHP to generate its own HTML tag for each page. All the pictures are in the ‘image’ folder and end with ‘Bg.jpg’.

<html style="
      background: url(images/'.$pic.'Bg.jpg) no-repeat center center fixed;
      -webkit-background-size: cover;
      -moz-background-size: cover;
      -o-background-size: cover;
      background-size: cover;
      filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/'.$pic.'Bg.jpg',     sizingMethod='scale');
      -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/'.$pic.'Bg.jpg', sizingMethod='scale')
";>

If you have only one background picture for all pages then you may remove the $pic variable, remove escaping back-slashes, adjust paths and place this code in your CSS file.

html{
    background: url(images/homeBg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/homeBg.jpg',     sizingMethod='scale');
    -ms-filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/homeBg', sizingMethod='scale');
}

This was tested with Internet Explorer 9, Chrome 21, and Firefox 14.

Popnoodles's user avatar

Popnoodles

27.9k2 gold badges44 silver badges53 bronze badges

answered Aug 6, 2012 at 13:41

Thorsten Niehues's user avatar

Thorsten NiehuesThorsten Niehues

13.4k20 gold badges75 silver badges111 bronze badges

1

Use this CSS:

background: url('img.png') no-repeat; 
background-size: 100%;

answered May 9, 2011 at 9:41

Rory Harvey's user avatar

Rory HarveyRory Harvey

2,5392 gold badges21 silver badges27 bronze badges

0

You can actually achieve the same effect as a background image with the img tag. You just have to set its z-index lower than everything else, set position:absolute and use a transparent background for every box in the foreground.

answered Jul 19, 2009 at 17:14

Kim Stebel's user avatar

Kim StebelKim Stebel

41.6k12 gold badges125 silver badges142 bronze badges

4

You can add this class into your CSS file.

.stretch {
    background: url(images/bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

It works in:

  • Safari 3 or later
  • Chrome Whatever or later
  • Internet Explorer 9 or later
  • Opera 10 or later (Opera 9.5 supported background-size, but not the keywords)
  • Firefox 3.6 or later (Firefox 4 supports non-vendor prefixed version)

Peter Mortensen's user avatar

answered Apr 17, 2015 at 7:57

Arunraj S's user avatar

Arunraj SArunraj S

7487 silver badges25 bronze badges

1

In order to scale your images appropriately based on the container size, use the following:

background-size: contain;
background-repeat: no-repeat;

Roman Snitko's user avatar

answered Jan 7, 2017 at 18:52

justinpees's user avatar

justinpeesjustinpees

3824 silver badges20 bronze badges

I use this, and it works with all browsers:

<html>
    <head>
        <title>Stretched Background Image</title>
        <style type="text/css">
            /* Remove margins from the 'html' and 'body' tags, and ensure the page takes up full screen height. */
            html, body {height:100%; margin:0; padding:0;}

            /* Set the position and dimensions of the background image. */
            #page-background {position:fixed; top:0; left:0; width:100%; height:100%;}

            /* Specify the position and layering for the content that needs to appear in front of the background image. Must have a higher z-index value than the background image. Also add some padding to compensate for removing the margin from the 'html' and 'body' tags. */
            #content {position:relative; z-index:1; padding:10px;}
        </style>
        <!-- The above code doesn't work in Internet Explorer 6. To address this, we use a conditional comment to specify an alternative style sheet for IE 6. -->
        <!--[if IE 6]>
        <style type="text/css">
            html {overflow-y:hidden;}
            body {overflow-y:auto;}
            #page-background {position:absolute; z-index:-1;}
            #content {position:static;padding:10px;}
        </style>
        <![endif]-->
    </head>
    <body>
        <div id="page-background"><img src="http://www.quackit.com/pix/milford_sound/milford_sound.jpg" width="100%" height="100%" alt="Smile"></div>
        <div id="content">
            <h2>Stretch that Background Image!</h2>
            <p>This text appears in front of the background image. This is because we've used CSS to layer the content in front of the background image. The background image will stretch to fit your browser window. You can see the image grow and shrink as you resize your browser.</p>
            <p>Go on, try it - resize your browser!</p>
        </div>
    </body>
</html>

Peter Mortensen's user avatar

answered May 2, 2012 at 14:39

Mahdi jokar's user avatar

Mahdi jokarMahdi jokar

1,2576 gold badges30 silver badges50 bronze badges

I wanted to center and scale a background image, without stretching it to the entire page, and I wanted the aspect ratio to be maintained. This worked for me, thanks to the variations suggested in other answers:

INLINE IMAGE: ————————

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

CSS ———————————-

html {
    height:100%;
}

#background {
    text-align: center;
    width: 100%; 
    height: 100%; 
    position: fixed;
    left: 0px; 
    top: 0px; 
    z-index: -1;
}

.stretch {
    margin: auto;
    height:100%;
}

Peter Mortensen's user avatar

answered Dec 24, 2010 at 13:05

AnnieDee's user avatar

AnnieDeeAnnieDee

911 silver badge1 bronze badge

0

Thanks!

But then it was not working for the Google Chrome and Safari browsers (stretching worked, but the hight of the pictures was only 2 mm!), until someone told me what lacks:

Try to set height:auto;min-height:100%;

So change that for your height:100%; line, gives:

#### #background {
    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1;
}

.stretch {
    width:100%;
    height:auto;
    min-height:100%;
}

Just before that newly added code I have this in my Drupal Tendu themes style.css:

html, body{height:100%;}

#page{background:#ffffff; height:auto !important;height:100%;min-height:100%;position:relative;}

Then I have to make a new block within Drupal with the picture while adding class=stretch:

< img alt=»» class=»stretch» src=»pic.url» />

Just copying a picture with the editor in that Drupal block doesn’t work; one has to change the editor to non-formatted text.

Peter Mortensen's user avatar

answered Apr 4, 2010 at 16:47

Cybr's user avatar

CybrCybr

811 silver badge1 bronze badge

I agree with the image in absolute div with 100% width and height. Make sure you set 100% width and height for the body in the CSS and set margins and padding to zero. Another issue you will find with this method is that when selecting text, the selection area can sometimes encompass the background image, which has the unfortunate effect of making the full page have the selected state. You can get round this by using the user-select:none CSS rule, like so:

<html>
    <head>
        <style type="text/css">

            html,body {
                height: 100%;
                width: 100%
                margin: none;
                padding: none;
            }

            #background {
                width: 100%;
                height: 100%;
                position: fixed;
                left: 0px;
                top: 0px;
                z-index: -99999;
                -webkit-user-select: none;
                -khtml-user-select: none;
                -moz-user-select: none;
                -o-user-select: none;
                user-select: none;
            }

            #background img {
                width: 100%;
                height: 100%;
            }

            #main{ z-index:10;}
        </style>
    </head>
    <body>
        <div id="main">
            content here
        </div>
        <div id="background"><img src="bg.jpg"></div>
    </body>
</html>

Again, Internet Explorer is the bad guy here, because it doesn’t recognise the user-select option — not even Internet Explorer 10 preview supports it, so you have the option of either using JavaScript to prevent background image selection (for example, http://www.felgall.com/jstip35.htm ) or using CSS 3 background-stretch method.

Also, for SEO I would put the background image at the bottom of the page, but if the background image takes too long to load (that is, with a white background initially), you could move to the top of the page.

Peter Mortensen's user avatar

answered Jul 6, 2011 at 10:38

Myke Black's user avatar

Myke BlackMyke Black

1,29915 silver badges15 bronze badges

1

I used a combination of the background-X CSS properties to achieve the ideal scaling background image.

background-size: cover;
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;

This makes the background always cover the entire browser window and remains centered when scaling.

Peter Mortensen's user avatar

answered Nov 12, 2018 at 4:02

Ryan Den-Kaat's user avatar

Use the Backstretch plugin. One could even have several images slide. It also works within containers. This way for example one could have only a portion of the background been covered with an background image.

Since even I could get it to work proves it to be an easy to use plugin :).

Peter Mortensen's user avatar

answered Sep 9, 2013 at 23:49

Daniel's user avatar

The following worked for me.

.back-ground {
   background-image: url("../assets/background.png");
   background-size: 100vw 100vh;
}

that worked to cover the entire background on different dimensions

answered Mar 25, 2020 at 21:07

tony2tones's user avatar

tony2tonestony2tones

1,2841 gold badge14 silver badges18 bronze badges

1

If you want to have the content centered horizontally, use a combination like this:

background-repeat: no-repeat;
background-size: cover;
background-position: center;

This will look beautiful.

Peter Mortensen's user avatar

answered Jan 29, 2019 at 22:12

Samuel Ramzan's user avatar

Samuel RamzanSamuel Ramzan

1,7141 gold badge15 silver badges24 bronze badges

Use this CSS:

background-size: 100% 100%

answered Nov 19, 2018 at 12:29

Shady Mohamed Sherif's user avatar

1

You can use the border-image : yourimage property to scale the image up to the border. Even if you give the background-image, the border image will be drawn over it.

The border-image property is very useful if your style sheet is implemented somewhere which doesn’t support CSS 3. If you are using Google Chrome or Firefox, then I recommend the background-size:cover property itself.

Peter Mortensen's user avatar

answered Jul 2, 2017 at 13:51

Natesh bhat's user avatar

Natesh bhatNatesh bhat

11.8k10 gold badges81 silver badges116 bronze badges

Do you want to achieve this just using one image? Because you can actually make somewhat similar to a stretching background using two images. PNG images for instance.

I’ve done this before, and it’s not that hard. Besides, I think stretching would just harm the quality of the background. And if you add a huge image it would slow down slow computers and browsers.

Peter Mortensen's user avatar

answered Jul 19, 2009 at 16:08

MarioRicalde's user avatar

MarioRicaldeMarioRicalde

8,9336 gold badges39 silver badges42 bronze badges

3

Свойство background-size масштабирует фоновое изображение, согласно заданным размерам.

Фон

  • background
  • background-attachment
  • background-blend-mode
  • background-clip
  • background-color
  • background-image
  • background-origin
  • background-position
  • background-position-x
  • background-position-y
  • background-repeat
  • background-size

Синтаксис¶

/* Keyword values */
background-size: cover;
background-size: contain;

/* One-value syntax */
/* the width of the image (height becomes 'auto') */
background-size: 50%;
background-size: 3.2em;
background-size: 12px;
background-size: auto;

/* Two-value syntax */
/* first value: width of the image, second value: height */
background-size: 50% auto;
background-size: 3em 25%;
background-size: auto 6px;
background-size: auto auto;

/* Multiple backgrounds */
background-size: auto, auto; /* Not to be confused with `auto auto` */
background-size: 50%, 25%, 25%;
background-size: 6px, auto, contain;

/* Global values */
background-size: inherit;
background-size: initial;
background-size: unset;

Значения¶

<размер>
Задаёт размер в любых доступных для CSS единицах — пикселях (px), сантиметрах (cm), em и др.
<проценты>
Задаёт размер фоновой картинки в процентах от ширины или высоты элемента.
auto
Если задано одновременно для ширины и высоты (auto auto), размеры фона остаются исходными; если только для одной стороны картинки (100px auto), то размер вычисляется автоматически исходя из пропорций картинки.
cover
Масштабирует изображение с сохранением пропорций так, чтобы его ширина или высота равнялась ширине или высоте блока.
contain
Масштабирует изображение с сохранением пропорций таким образом, чтобы картинка целиком поместилась внутрь блока.

Если установлено одно значение, оно устанавливает ширину фона, второе значение принимается за auto. Пропорции картинки при этом сохраняются. Использование двух значений через пробел задаёт ширину и высоту фоновой картинки.

Значение по-умолчанию:

Применяется ко всем элементам

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

  • CSS Backgrounds and Borders Module Level 3

Поддержка браузерами¶

Can I Use background-img-opts? Data on support for the background-img-opts feature across the major browsers from caniuse.com.

Описание и примеры¶

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>background-size</title>
    <style>
      div {
        height: 200px; /* Высота блока */
        border: 2px solid #000; /* Параметры рамки */
        background: url('/example/image/mybg.png') 100% 100%
          no-repeat; /* Добавляем фон */
        background-size: cover; /* Масштабируем фон */
      }
    </style>
  </head>
  <body>
    <div>...</div>
  </body>
</html>

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить размер флешки через командную строку
  • Как изменить размер флешки на реальный
  • Как изменить размер флешки на меньший
  • Как изменить размер флешки usb
  • Как изменить размер флекс элемента

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии