Background the zoom
Recently, I met such a problem in an interview. I needed to spread out a 750×750 picture to make a big screen on the official website, which seemed high-end and arrogant. However, throughout the author’s experience, background images of similar portal official websites are usually made in accordance with the general large size and zoom ratio, and I have rarely seen such small size 750*750. Well, let’s try it out:
.bg {
background-image: url('./bt-home.d2a41ff9.webp');
background-size: 100% 100%;
background-repeat: no-repeat;
}
Copy the code
This one is rather simple and crude, and gives the following effect:
The only fly in the ointment is that the background doesn’t scale as the window scales, such as the screen width being too narrow:Or too narrow a height:Under these Windows the whole picture will look very ugly, so how to improve? So I wrote two more lines of style
.bg { background-image: url('./bt-home.d2a41ff9.webp'); background-size: 100% 100%; background-repeat: no-repeat; background-size: cover; // Add background-position: bottom; // new}Copy the code
To see the overall effect:When the width is too narrow:In the case of too narrow height:
And scaling the background as the window scales looks much better than before. Let’s see what happens with the two lines. Let’s look at background-size
background-size: cover; At this point, the aspect ratio of the image is maintained and the image is scaled to the minimum size that will completely cover the background location area.Copy the code
This means that the aspect ratio is scaled according to the current maximum background area. If the window width is wide and the height is narrow, the vertical area of the background will be hidden, and vice versa. Anyway, it makes the background very elastic and spread out. Let’s look at background-position
background-position: bottom; // Specify where the background should be placedCopy the code
Attribute values can be written in many ways:So it is also equivalent to writing:
background-position: bottom center; // Specify where the background should be placedCopy the code
Let’s remove background-size: cover and see how the position is changed:Before changing location:Since the main content of this picture is the buildings and streets below, the position is changed to bottom and center, so that the content can be retained in the view compared with the default background-position. In this case, the scaling direction will be from bottom to top. The combination of the two can maintain elastic scaling while retaining key background content.
conclusion
CSS is a black magic box again, can put this black magic box into their Arsenal that is the real front-end design master bar