How to set up smartphones and PCs. Informational portal
  • home
  • Iron
  • Changing the css background size. Controlling the size of the background image with css

Changing the css background size. Controlling the size of the background image with css

One of the most commonly used css properties in website layout is the background property of the page element. Today we will talk with you about how you can resize background image with help .

In more old version CSS 2.1 background image applied to a container retained its fixed dimensions. It was impossible to change the size of the background image. Fortunately, CSS3 introduced the background-size property, which can be used to stretch or shrink the background.

There are several ways to determine the dimensions -.

Absolute resizing

If only one value is specified, it is assumed to be the width. The height is set to auto and the aspect ratio is preserved:

This code scales the image from 200x200 to 100x100 pixels.

Relative resizing through percentages

If percentages are applied, the dimensions are based on the element, NOT the image:

background fill

The background-size property also understands keyword cover. The image will be scaled to fill the entire container, but if the aspect ratio differs, the image will be cropped.

:cover;

Scaling multiple backgrounds

Multiple backgrounds can be scaled using a comma-separated list of values ​​in the same order.

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

All latest versions browsers support the background-size property.

Conclusion

Well, now we know how to control the size of the background image using cascading style sheets.

Don't forget to subscribe to blog updates so you don't miss new interesting articles.

One of the main tasks in adaptive layout is the scaling of images (including background images) in such a way that they are correctly displayed on devices with different permissions screens.

With pictures in tag img it's simple: when setting the width as a percentage, the height will be scaled automatically. This method cannot be applied to the background image.

This trick is to set the value as a percentage of the padding ( padding) element. The method was first published in an old blog post A List Apart , but it still works well.

Let's say we have an 800 x 450 pixel background image, and we want to make it the background with a fixed aspect ratio of 16:9. The code below uses for indentation px, but everything will work with em. There is also an HTML5 figure element, for correct operation older browsers can use HTML5 shiv .

Div.column ( max-width: 800px; ) figure.fixedratio ( padding-top: 56.25%; /* 450px/800px = 0.5625 */ )

Adding a background

The resulting element scales as it should, but if you add a background image, the result will not be very good. Using the attribute background-size: cover. Unfortunately, in Internet Explorer 8 this method does not work. To solve this problem, we position the background with background position. background picture must be at least as wide as max-width element. Otherwise, the image will be cropped.

Div.column ( /* The background image must be 800px wide */ max-width: 800px; ) figure.fixedratio ( padding-top: 56.25%; /* 450px/800px = 0.5625 */ background-image: url(http://voormedia.com/examples/north-sea-regatta.jpg); background-size: cover; -moz-background-size: cover; /* Firefox 3.6 */ background-position: center; /* Internet Explorer 7/8 */ )

Let's say we have a large background image that looks great on desktop. But on mobile device it will be too small, so right decision will decrease the width of the background.

For example, a picture with a width of 800 by 200 pixels (4:1) on small screen, at 300px wide, should scale down to 150px (2:1). Let's count the attributes height and padding top:

The figure shows the aspect ratio of the background image at different widths. The slope of the graph (slope) corresponds to the attribute padding top, start height - attribute height. The result is the code:

Div.column ( /* The background image must be 800px wide */ max-width: 800px; ) figure.fluidratio ( padding-top: 10%; /* slope */ height: 120px; /* start height */ background- image: url(http://voormedia.com/examples/amsterdam.jpg); background-size: cover; -moz-background-size: cover; /* Firefox 3.6 */ background-position: center; /* Internet Explorer 7/8 */ )

Using SCSS to Calculate

Attributes padding top and height can be calculated automatically using preprocessors such as SCSS. An example of this:

/* Calculate fluid ratio based on two dimensions (width/height) */ @mixin fluid-ratio($large-size, $small-size) ( $width-large: nth($large-size, 1); $width -small: nth($small-size, 1); $height-large: nth($large-size, 2); $height-small: nth($small-size, 2); $slope: ($height- large - $height-small) / ($width-large - $width-small); $height: $height-small - $width-small * $slope; padding-top: $slope * 100%; height: $height ; background-size: cover; -moz-background-size: cover; /* Firefox 3.6 */ background-position: center; /* Internet Explorer 7/8 */ ) figure.fluidratio ( /* This element will have fluid ratio from 4:1 at 800px to 2:1 at 300px.*/ @include fluid-ratio(800px 200px, 300px 150px); background-image: url(http://voormedia.com/examples/amsterdam.jpg); )

Web technologies, as well as various design trends, do not stand still, so every time some original features and nuances for sites appear. One of these "directions" is the use of a background (backgorund), which stretches to fill the screen in width and height. I told something like about a year ago or more - the image was placed in the blog header and smoothly “transitioned” into the main background color web pages. You can even add .

Placing a large scalable image as a background is something new and more difficult, the solution of which I found in this article.

Target this lesson place a background image on the site that would permanently cover the entire background of the browser window. What exactly needs to be done:

  • fill the entire page with one image without spaces;
  • resizing the image if necessary (reducing the browser window);
  • maintaining image proportions;
  • positioning the image in the center of the page;
  • lack of scroll bars on the page;
  • cross-browser solution suitable for different browsers;
  • implementation without any third-party technologies such as flash.

So, there are several suitable solutions for the background of the site in full screen.

Wonderful, simple and progressive solution with CSS3

To accomplish this task, we can use the background-size property in CSS3. We will use an html element that is better than body. Let's set a fixed and centered background, after which we will use the background-size value of cover.

html ( 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;)

html ( 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 solution is supported by almost all popular on the network:

  • Firefox 3.6+ (Firefox 4 supports non-vendor prefixed version)
  • Opera 10+ (Opera 9.5 supports background-size but no cover value)
  • Chrome Whatever+
  • IE9+
  • Safari 3+

A certain Goltzman found a solution that allows the hack to work in IE

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

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

But attention!!! this may cause some problems with the work of links on the page. By the way, a little later Matt Litherland added that the code, in principle, can be used but cannot be used for this html elements or body and you need to implement everything through a div with 100% height and width.

css-hack number 1

An alternative version is presented by Doug Neiner. In this case, the element embedded in the page is used. , which can be resized in any browser. Set a min-height value that encourages the browser window to fill vertically, and set width to 100%, which fills the page horizontally. We also set the min-width so that the image is never smaller than it really is.

img.bg ( /* Set rules to fill background */ min-height : 100% ; min-width : 1024px ; /* Set up proportionate scaling */ width : 100% height : auto ; /* Set up positioning */ position : fixed ; top : 0 ; left: 0 ) @media screen and (max-width : 1024px ) ( /* Specific to this particular image */ img.bg ( left : 50% ; margin-left : -512px ; /* 50% */ ) )

img.bg ( /* Set rules to fill background */ min-height: 100%; min-width: 1024px; /* Set up proportionate scaling */ width: 100%; height: auto; /* Set up positioning */ position: fixed; top: 0; left: 0; ) @media screen and (max-width: 1024px) ( /* Specific to this particular image */ img.bg ( left: 50%; margin-left: -512px; /* fifty% */ ) )

Works in any versions of high-quality browsers - Safari / Opera / Firefox and Chrome. For IE, as always, there are some nuances:

  • IE 9 - works;
  • IE 7/8 - most often functions correctly, but does not center images smaller than the browser window;
  • IE 6 - can be customized, but who needs this browser at all.

css-hack option 2

Another way to solve the problem with CSS styles is to place an inline image on the page with a fixed position on the left upper corner, then set the min-width and min-height to 100% while keeping the aspect ratio.

#bg ( position : fixed ; top : -50% ; left : -50% ; width : 200% ; height : 200% ; ) #bg img ( position : absolute ; top : 0 ; left : 0 ; right : 0 ; bottom : 0 ; margin : auto ; min-width : 50% ; min-height : 50% ; )

#bg ( position:fixed; top:-50%; left:-50%; width:200%; height:200%; ) #bg img ( position:absolute; top:0; left:0; right:0; bottom:0; margin:auto; min-width:50%; min-height:50%; )

The hack works in:

  • Safari / Chrome / Firefox (too early versions not tested, but works well in the latest)
  • IE8+
  • Opera (any version) and together with IE both both are buggy in the same way with a positioning error.

Method with jQuery

This option is much easier (in terms of CSS) if we know that the aspect ratio of the image (img is used as the background) is larger or smaller than the current aspect ratio of the browser window. If less, then we can only use width = 100% and at the same time the window will be equally filled in width and height. If more, you can specify only height = 100% to fill the entire window.

Access to all data is coming via JavaScript, the codes used are the following:

#bg ( position : fixed ; top : 0 ; left : 0 ; ) .bgwidth ( width : 100% ; ) .bgheight ( height : 100% ; )

#bg ( position: fixed; top: 0; left: 0; ) .bgwidth ( width: 100%; ) .bgheight ( height: 100%; )

< aspectRatio) { $bg .removeClass() .addClass("bgheight"); } else { $bg .removeClass() .addClass("bgwidth"); } } theWindow.resize(function() { resizeBg(); }).trigger("resize"); });

$(window).load(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"); });

In my opinion, centering is not performed in this case (as far as I understand), but it can be done. Most desktop browsers are supported, including IE7+. Finally, the author of the article about hacks has prepared a set of example files in which all this is implemented - you can download it. The comments on the original article also provide some information and discussion, although most important details the author added in the form of updates to the post and I also have it translated and indicated. Of course, examples will help to understand all this. In general, if it were not for the constant "gags" from IE7, all the hacks mentioned would be perfect.

P.S. Do you want to buy a book? - it is not necessary to go to the store, because now the online bookstore allows you to do everything through the network - choose, pay and arrange home delivery.

The resolution of monitors is constantly growing and when laying out web pages, you have to take into account the most wide range permissions. This is especially important when using background picture, which is either cut off at a low monitor resolution, or, conversely, does not fit entirely at high resolution. One solution similar situation is background scaling. Of course, this promises some troubles, such as the appearance of distortions and artifacts in images, but it also expands the arsenal of layout tools.

The background-size property controls the size, the cover keyword can be specified as a value, then the image size will be such that its width and height fit in the specified area (for example, a web page window); the contain keyword scales the image so that at least one side of the image fits entirely within the specified area. In addition, it is permissible to indicate explicit dimensions horizontally or vertically as a percentage or other css units. On fig. 1 shows the resizing of images when different meanings background-size . gray a block of 280x200 pixels is selected, inside which the background is set.

Rice. 1. Appearance of background images depending on background-size value

If two size values ​​are specified, separated by a space, then the first value determines the horizontal width, and the second vertically. In this case, the proportions are ignored, which is clearly seen in Fig. 1g Instead of one of the sizes, it is permissible to use the keyword auto , then the browser calculates it automatically, based on the proportions of the image.

Example 1 sets background photo, which takes up the entire browser window.

Example 1. Background image

Background scaling

Result this example shown in fig. 2. When resizing the window, the photo will grow or shrink to fill the entire web page.

The resolution of monitors is constantly growing, and when laying out web pages, you have to take into account the widest range of resolutions. This is especially important when using a background image that is either cut off at a low monitor resolution, or, conversely, does not fit entirely at a high resolution. One solution to this situation is to scale the background. Of course, this promises some troubles, such as the appearance of distortions and artifacts in images, but it also expands the arsenal of layout tools.

The background-size property is responsible for controlling the size, the cover keyword can be specified as a value, then the image size will be such that its width and height fit in the specified area (for example, a web page window); the contain keyword scales the image so that at least one side of the image fits entirely within the specified area. It is also acceptable to specify explicit horizontal or vertical dimensions in percentages or other CSS units. On fig. Figure 1 shows image resizing with different background-size values. A block of 280x200 pixels in size is highlighted in gray, inside which the background is set.

Rice. 1. Appearance of background images depending on background-size value

If two size values ​​are specified, separated by a space, then the first value determines the horizontal width, and the second vertically. In this case, the proportions are ignored, which is clearly seen in Fig. 1g Instead of one of the sizes, it is permissible to use the keyword auto , then the browser calculates it automatically based on the aspect ratio of the image.

Example 1 sets a background photo that takes up the entire browser window. To do this, I had to set the height of html and body as 100%.

Example 1. Background image

HTML5 CSS3 IE 9+ Cr Op Sa 5 Fx

Background scaling

The background also includes a gradient, which can also be scaled, thereby obtaining a variety of effects. For example, by adding background-size to linear gradient, we will make it repeat, which forms alternating gradient stripes (example 2).

Example 2 vertical stripes

Gradient

The result of the example is shown in Fig. 2.

Rice. 2. Vertical gradient stripes

Vertical and horizontal stripes can be made not only with gradient, but also with clear edges. To do this, four colors must be specified in the gradient parameters - from 0 to 50% the color of the first stripe and from 50% to 100% the color of the second stripe. The first color with 0% and the last color with 100% can be omitted, they are added automatically by the browser, so we will limit ourselves to only two values. Example 3 shows the creation horizontal stripes 50 pixels high.

Example 3: Horizontal stripes

HTML5 CSS3 IE 10+ Cr Op Sa Fx

Gradient

The result of this example is shown in Fig. 3.

Rice. 3. Horizontal stripes

Since you can add multiple backgrounds at the same time by listing their parameters separated by commas, you can do the same with gradients. Only one of the colors should be semi-transparent, otherwise the gradients will overlap each other. Example 4 uses two gradients intersecting at right angles for the background of the web page, which in combination with background-size creates cells.

Example 4: Two gradients

HTML5 CSS3 IE Cr Op Sa Fx

Gradient

The result of this example is shown in Fig. 4.

Rice. 4. Cells

The combination of the gradient and the background-size property allows you to get a wide variety of background fills created without the use of background images.

Top Related Articles