Home  >  Article  >  Web Front-end  >  How to Stretch a Background Image to Fill an Element in CSS?

How to Stretch a Background Image to Fill an Element in CSS?

Linda Hamilton
Linda HamiltonOriginal
2024-11-07 04:14:02127browse

How to Stretch a Background Image to Fill an Element in CSS?

Stretching Background Images in CSS

Want your background image to occupy the entire space of an element like a , but can't seem to get it to stretch properly? Here's a simple CSS solution.

The provided CSS script defines a class called "style1" with the following properties:

.style1 {
  background-image: url('http://localhost/msite/images/12.PNG');
  background-repeat: no-repeat;
  background-position: left center;
}

While this will display the background image on the element, it won't stretch it to fill the entire cell. To achieve this, we need to modify the background property:

.style1 {
  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;
}

The background-size: cover property ensures that the background image is resized to cover the entire element, without distorting its aspect ratio. To make the image stay in place, we use background-position: center center and background-attachment: fixed.

This solution works in a wide range of browsers, including Safari, Chrome, IE 9 , Opera 10 , and Firefox 3.6 .

For Internet Explorer, an alternative solution can be used:

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

This uses a proprietary filter to stretch the background image, but it is only supported in IE.

Credits: Chris Coyier's article "Perfect Full Page Background Image" at http://css-tricks.com/perfect-full-page-background-image/

The above is the detailed content of How to Stretch a Background Image to Fill an Element in CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn