Image with background and content in the foreground

Verze:

03. 03. 2022

Zodpovědná osoba:

Dominik Šlechta

The background image is set using the absolute position. Absolute position ignores the layout of other components, while the absolute position block ignores other elements on the page.

Z-index allows us to set what will be in the foreground and what will be in the background. The z-index always works relative to the parent. This means that if we have two sections with different nesting, the z-index will probably not work properly. It is important that the elements are in the same parent.

   {* Article | Figure *}
    
    <div class="article__figure --flex --flex-column --flex-end-x">
        <a class="article__figure-link" href="{$item|link}" n:if="$img">
            <img class="article__img" src="{$img}" alt="{$item|name|striptags}">
        </a>

        <div class="article__author">

        </div>
    </div>

In this case, the article figure is fixed to 255px, the parent of the absolute element must have position:relative, otherwise the absolute element will be positioned according to the nearest ancestor of the class.

Width and height at 100% + object-fit cover behaves the same as background-size:cover, allowing us to add an image that keeps the aspect ratio and overlays the section.

The gradient in this case is set as pseudoelement &::after.

.article__figure {
	width: 255px;
	height: 255px;
	position: relative;
	flex-shrink: 0;
	z-index: 1;
	padding: 18px 25px;
	
	&::after{
		@include pseudo(block, absolute);
		background: linear-gradient(to top, #000 0%, transparent 60%);
		top:0;
		left:0;
		width: 100%;
		height: 100%;
		position: absolute;
		z-index: 0;
		pointer-events: none;
	}
}

.article__author{
	z-index: 2;
}
.article__img{
	position: absolute;
	left:0;
	top:0;
	width: 100%;
	height: 100%;
	object-fit: cover;
}