Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center fixed background of container

I want to create a header with a fixed background. So I defined the following properties:

header {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 300px;
    display: block;
    background-image: url('...');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    background-attachment: fixed;
}

Now I have the following problem. Currently, the background is centered according to the Screen Width and Height. Since the header is at the top, the actual background of the header is just the top of the image. In addition, the header image section changes every time I change the screen height, which is not my goal.

I want the image to be centered within the header (center of the image is at the center of the header, but only if I have not scrolled down). In addition, the header image section should only change if I change the header width, height or screen width but not if the screen height is changed.

like image 299
Kaskorian Avatar asked Jan 21 '26 18:01

Kaskorian


1 Answers

You can rely on vh unit combined with some calc(). The center is initally 50vh and you want it to be 150px from the top so we need a translation of 50vh - 150px. You should also get rid of cover if you want the image to not change when the screen height change but it may not render like you want.

I replaced 300px with 100px for the demo.

.header {
  height:100px;
  border:1px solid;
  background:
    url(https://picsum.photos/id/1014/1200/800) 50% calc(50% - (50vh - 50px)) fixed;
}
.not-fixed {
  background-attachment:initial;
  background-position:center;
  margin-top:20px;
}

body {
  min-height:200vh;
  margin:0;
}
<div class="header">

</div>
<div class="header not-fixed">

</div>

With the use of cover

.header {
  height:100px;
  border:1px solid;
  background:
    url(https://picsum.photos/id/1014/1200/800) 50% calc(50% - (50vh - 50px))/cover fixed;
}
.not-fixed {
  background-attachment:initial;
  background-position:center;
  margin-top:20px;
}

body {
  min-height:200vh;
  margin:0;
}
<div class="header">

</div>
<div class="header not-fixed">

</div>

You can clearly see how the first image is centred exactly like the second one without fixed

To get more details about the caluclation check this: Using percentage values with background-position on a linear gradient (the section Combining pixel and percentage values)

like image 120
Temani Afif Avatar answered Jan 24 '26 10:01

Temani Afif