CSS trick for styling a full-width image inside a container-element

14 July 2019

css-tricks

A container is used to group elements and structures a website in different areas. For example, the text you are reading right now is placed inside a container. The container keeps the text within its width.

Now, if we want to have a full-width image in between the text, there are two ways of I can think of. The first one would be splitting the container into two and placing the image in between. While this works fine, it isn't a very convenient solution, especially when having many images.

Instead, we use the CSS calc function to calculate the needed margin for our images:
.img-full { margin: 0 calc(50% - 50vw); }

What happens here is we're taking the 50% width of the container and subtracting 50% of the current viewport width (50vw), which is pulling the image left to the start of the screen. We also add a fix height and object-fit: cover. The full class looks like this:

You probably notice a horizontal scroll bar appearing. That's because 50% of the viewport width also includes the width of the vertical scroll bar. To get around this issue add overflow-x: hidden; to the body.

css-tricks