Today, I saw an activity page on smartisan’s official website. Its content layout made me learn.

.wrapper-banner
    .content-banner
        img
        a.hot
        a.hot
Copy the code

.wrapper-banner is a normal div block element; . Content-banner is relative; Img is a large image, 2560px wide; A. hot is an absolute positioning element that uses left, top, width, and height to lock an area of the image as the click area (there are two items in the image, so there are two a. hots).

The. Content-banner is set to 2560px wide (the same as the original width of the inner image) so that the inner image will be displayed as it should be. But there’s a problem:

The IMG image is wide, the activity is in the middle of the image, and there is an equal amount of white space on both sides. How do I center the image?

It’s like this

.content-banner {
    width: 2560px;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
}
Copy the code

Position is a relative element that contains the nearest block container, i.e..wrapper-banner. The left of the percentage value is offset with respect to the containing block width. Now the question is: what is the wrapper-banner width?

Answer: the.wrapper-banner width is the width of the parent element because the block element is full by default. Note that it is not 2560px that IMG struts! It’s easy to get this wrong (I did).

It also makes sense to give the.wrapper-banner a background color and slide the horizontal scroll bar right (inside the img spread) to see that the background color does not cover a wider area outside the screen.

For the current scenario:.wrapper-banner is the width of the current viewport, or the width of a screen.

left: 50%; Let the left edge of the.Content-banner be in the middle of the screen. Then use translateX(-50%). The.content-banner is offset to the left by 50% of its own width (should be relative to the element’s border box)! The picture is now centered. Of course, any part of the image that is offset beyond the left edge of the screen is captured (of course, otherwise you can scroll the scrollbar back to the left! ?).

Finally, give.wrapper-banner a overflow: hidden; So the horizontal scroll bar disappears.

The final usage style is as follows:

.wrapper-banner {
    overflow: hidden;
}

.content-banner {
    width: 2560px;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
}

.content-banner img {
    display: block;
    width: 100%;
}
Copy the code

(after)