Как сделать изображение на весь фон css

Stretch and scale CSS background

To preserve the aspect ratio of the image you should use «background-size: cover;» or «background-size: contain;». I’ve built a polyfill that implements those values in IE8: github.com/louisremi/background-size-polyfill

I know this is a year old but I have to (laugh and) agree with the ‘decent browsers’ part. Check all of your browsers but I’ve had more issues with IE than any of them.

I had to set background-size: 100% 100%; to get the desired effect I was going for, if that helps anyone else.

this doesn’t actually work. The question is to fill the container which means we want it to stretch so it doesn’t repeat. This answer on the other hand will repeat in the height direction if the height doesn’t cover the area. «Stretch to fill» means stretch however you have to so it doesn’t repeat. The correct answer is «cover» from below. That actually handles the case that this doesn’t.

For modern browsers, you can accomplish this by using background-size :

cover means stretching the image either vertically or horizontally so it never tiles/repeats.

That would work for Safari 3 (or later), Chrome, Opera 10+, Firefox 3.6+, and Internet Explorer 9 (or later).

For it to work with lower verions of Internet Explorer, try these CSS:

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')"; 

To Clement: What you suggest for filters for previous IE:s work only partly. It scales the picture width ok but the height scaling goes wrong by not restricting it to anything. The higher the page so is the background picture.. =( I tried this on IE8. And also, could it be in anyway possible use these ‘cover’ commands and somehow make this compatible with mobiles like iphone? I know there is the viewport problem but could it be possibke to scale the viewport to whole screen in a way that background is scaled here?? Thanks for responses!

The IE-specific filters are not ideal solutions so feel free to condition for IE with CSS alternatives. I personally use the CSS3 «cover» on my own site and it works fine on iOS devices, just be sure to define the device-width.

NB: As of Chromium 78.0.3904.97, it is not possible to scale svg images independently along each axis. You may have to scale it up and convert it to a raster image.

Scaling an image with CSS is not quite possible, but a similar effect can be achieved in the following manner, though.

In order to scale the image to be «full bleed» and maintain the aspect ratio, you can do this instead:

It works out quite nicely! If one dimension is cropped, however, it will be cropped on only one side of the image, rather than being evenly cropped on both sides (and centered). I’ve tested it in Firefox, Webkit, and Internet Explorer 8.

Читайте также:  Css background image color position

This works well. but was looking for something a little more robust (probably with javascript) that also centered it and adjusted based on if the picture was landscape or portrait. If anyone has a solution in that vein would love a link. thanks!

Horizontal centering can be done with margin: 0 auto on .stretch . By only setting the width or height , the aspect ratio stays the same. Try using max-width and max-height to limit the zoom-factor.

This doesn’t work for me in ie8/ie9, but works in ie6/ie7 (and of course all other browsers). In ie8/ie9, the image only shows up for about 3/4 of the div. Anybody have the same issue?

A flaw with SO: there’s no way to mark answers which are no longer correct, leading to people like @Ullas being led astray. It’s easy to scale backgrounds in all modern browsers. developer.mozilla.org/en/CSS/background-size

EDIT: Modernizr supports detection of background-size support. You can use a JavaScript workaround written to work however you need it and load it dynamically when there is no support. This will keep the code maintainable without resorting to intrusive CSS hacks for certain browsers.

Personally I use a script to deal with it using jQuery, its an adaption of imgsizer. As most designs I do now use width %’s for fluid layouts across devices there is a slight adaptation to one of the loops (accounting for sizes that aren’t always 100%):

for (var i = 0; i < images.length; i++) < var image = images[i], width = String(image.currentStyle.width); if (width.indexOf('%') == -1) < continue; >image.origWidth = image.offsetWidth; image.origHeight = image.offsetHeight; imgCache.push(image); c.ieAlpha(image); image.style.width = width; > 

EDIT: You may also be interested in jQuery CSS3 Finaliz[s]e.

Just to emphasize, Modernizr does NOT enable support for background-size in browsers that don’t natively support it. It just has a convenient cross-browser test for it. It’s up to you to fake it when the test returns false.

Try the article background-size. If you use all of the following, it will work in most browsers except Internet Explorer.

If the background image is an SVG, it is also necessary to specify preserveAspectRatio=»none» within the SVG. More info about this here. Demo here.

  • Safari 3+
  • Chrome Whatever+
  • IE 9+
  • Opera 10+ (Opera 9.5 supported background-size but not the keywords)
  • Firefox 3.6+ (Firefox 4 supports non-vendor prefixed version)

In addition you can try this for an ie solution

 filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')"; zoom:1; 

@PKHunter , im not sure exactly what you are reffering to. This is using background-size: cover except with browser prefixeds and a IE solution

Not currently. It will be available in CSS 3, but it will take some time until it’s implemented in most browsers.

There is a reason the date is shown. It should be kept for historical references. Are you going over all the old answers on the site and downvoting them? the answer is still correct even if more information has been added since then. Also note that other answers here basically state the same (and some are indeed incorrect — they state it’s impossible). I get the feeling you picked on this one since it has some votes.

Читайте также:  Python конвертировать секунды во время

No, I picked on this one since all it does is say «Computer say no» even though there are several solutions to this problem even back in 2008 😉

In one word: no. The only way to stretch an image is with the tag. You’ll have to be creative.

This used to be true in 2008, when the answer was written. Today modern browsers support background-size which solves this problem. Beware that IE8 doesn’t support it.

If you’ve got a bitmap format, it’s generally not great (graphically speaking) to stretch it and pull it about. You can use repeatable patterns to give the illusion of the same effect. For instance if you have a gradient that gets lighter towards the bottom of the page, then you would use a graphic that’s a single pixel wide and the same height as your container (or preferably larger to account for scaling) and then tile it across the page. Likewise, if the gradient ran across the page, it would be one pixel high and wider than your container and repeated down the page.

Normally to give the illusion of it stretching to fill the container when the container grows or shrinks, you make the image larger than the container. Any overlap would not be displayed outside the bounds of the container.

If you want an effect that relies on something like a box with curved edges, then you would stick the left side of your box to the left side of your container with enough overlap that (within reason) no matter how large the container, it never runs out of background and then you layer an image of the right side of the box with curved edges and position it on the right of the container. Thus as the container shrinks or grows, the curved box effect appears to shrink or grow with it — it doesn’t in fact, but it gives the illusion that is what’s happening.

As for really making the image shrink and grow with the container, you would need to use some layering tricks to make the image appear to function as a background and some javascript to resize it with the container. There’s no current way of doing this with CSS.

If you’re using vector graphics, you’re way outside my realm of expertise I’m afraid.

Источник

Фон, который всегда растягивается на всю страницу

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

Подобный урок уже приводился на сайте RUSELLER.COM. Но с того момента прошло время и наступила пора обновить и расширить список используемых методов.

  • Заполнять изображением всю страницу без пробелов.
  • Масштабировать изображение, если нужно.
  • Сохранять пропорции изображения.
  • Изображение центрируется на странице.
  • Изображение не создает никаких полос прокрутки.
  • Кросс-браузерное решение по возможности.
  • Не использовать никаких сторонних технологий, например, Flash.

sourse

Удивительный, простой и прогрессивный метод CSS3

Задача легко решается с помощью CSS3 благодаря ставшему доступным свойству background-size . Мы используем элемент html (лучше, чем body , так как он всегда имеет, по крайней мере, высоту окна браузера). Устанавливаем фиксированные и центрированный фон для него, а затем настраиваем размер с помощью присваивания свойству background-size ключевого слова cover.

  • Safari 3+
  • Chrome
  • IE 9+
  • Opera 10+ (Opera 9.5 поддерживает свойство background-size, но без ключевых слов)
  • Firefox 3.6+
Читайте также:  Сайт начинающего верстальщика

Техника с использованием только CSS. Часть #1.

Используем строчный элемент , размеры которого можно менять в любом браузере. Устанавливаем свойство min-height , чтобы заполнить окно браузера вертикально, а свойству width присваиваем значение 100% для заполнения по горизонтали. Также устанавливаем свойство min-width равным ширине изображения, чтобы никогда оно не уменьшалось.

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

img.bg < /* Устанавливаем правила для заполнения фоном */ min-height: 100%; min-width: 1024px; /* Устанавливаем коэффициент пропорциональности */ width: 100%; height: auto; /* Устанавливаем позиционирование */ position: fixed; top: 0; left: 0; >@media screen and (max-width: 1024px) < /* Определяется свое для каждого конкретного изображения */ img.bg < left: 50%; margin-left: -512px; /* 50% */ >>
  • Любой версии нормального браузера: Safari / Chrome / Opera / Firefox.
  • IE 6: Не работает — но можно использовать какой-нибудь из трюков для позиционирования.
  • IE 7/8: В большинстве случаев работает, не центрирует маленькие изображения, но заполняет экран правильно.
  • IE 9: Работает.

Техника с использованием только CSS. Часть #2.

Другой способ решить задачу — поместить строчный элемент на странице, зафиксировать его положение в левом верхнем углу и установить значение 100% для его свойств min-width и min-height , сохраняя коэффициент пропорциональности.

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

  • Safari / Chrome / Firefox (не тестировалось на всех версиях, но в последних работает прекрасно).
  • IE 8+.
  • Opera (любая версия) и IE отказываются работать с данным способом (неправильное позиционирование изображения).

Используем jQuery

Идея очень проста, если коэффициент пропорциональности изображения (строчный элемент будет использоваться как фон) сопоставляется с коэффициентом пропорциональности окна браузера. Если для изображения он меньше, то нужно присвоить только свойству изображения width значение 100%, и оно будет заполнять экран и по высоте и по ширине. А если больше, то присвоить только свойству изображения height значение 100%.

$(function() < var theWindow = $(window), $bg = $("#bg"), aspectRatio = $bg.width() / $bg.height(); function resizeBg() < if ( (theWindow.width() / theWindow.height()) < aspectRatio ) < $bg .removeClass() .addClass('bgheight'); >else < $bg .removeClass() .addClass('bgwidth'); >> theWindow.resize(function() < resizeBg(); >).trigger("resize"); >);

Заключение

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

Данный урок подготовлен для вас командой сайта ruseller.com
Источник урока: css-tricks.com/perfect-full-page-background-image/
Перевел: Сергей Фастунов
Урок создан: 14 Декабря 2010
Просмотров: 136017
Правила перепечатки

5 последних уроков рубрики «CSS»

Забавные эффекты для букв

Реализация забавных подсказок

Небольшой концепт забавных подсказок, которые реализованы на SVG и anime.js. Помимо особого стиля в примере реализована анимация и трансформация графических объектов.

Анимированные буквы

Солнцезащитные очки от первого лица

Прикольный эксперимент веб страницы отображение которой осуществляется “от первого лица” через солнцезащитные очки.

Источник

Оцените статью