Position the background of the container in the center and keep it

I am trying to create a fixed background header using the following CSS 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;
}

However, I am facing an issue where the background image is centered based on screen width and height. This results in only the top portion of the image being displayed as the actual background of the header. Additionally, the position of the header image changes whenever the screen height is adjusted, which is not what I intended.

What I want is for the image to be perfectly centered within the header, with the center of the image aligning with the center of the header (without any scrolling). Furthermore, I would like the header image position to adjust only when the header's dimensions or screen width change, without any impact from changes in screen height.

Answer №1

For precise centering of an image, you can leverage the vh unit along with some calc() function. Initially, set the center at 50vh, then adjust it to be 150px from the top by calculating 50vh - 150px. Removing cover allows the image to remain fixed relative to the screen height changes, but this may affect the rendering.

I substituted 300px with 100px for demonstration purposes.

.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>

Utilizing 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>

The alignment of the first and second images appears identical without using fixed.

To delve deeper into the calculation details, refer to: Using percentage values with background-position on a linear gradient (specifically the section Combining pixel and percentage values).

Answer №2

Experiment by wrapping the image (outside the header div) and the header div, then play around with position relative or absolute to overlay the header on top of the image.

Once you've accomplished that, utilize z-index to move the image further back in the display order.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a circle at the point where two table cells intersect in an HTML document

How can I create a circular shape at the intersections of HTML tables? I am struggling to figure out a way to incorporate shapes into HTML tables. My goal is to achieve a design similar to the image shown below. I have attempted using text and spans, as we ...

The text-decoration is here to stay

Currently, I am facing an issue with the customization of a wordpress theme related to the styling of links within posts. Although I have tried to change the color and remove underlining using CSS rules, I am unsuccessful so far: a, .entry-meta a, entry-c ...

Achieve a new line break when the user hits the "Enter" key using HTML and JavaScript

I'm in the process of developing a Chrome Extension that allows users to create a to-do list. My goal is to enable users to submit their task by pressing the "Enter" key, which should move the task to the next line after submission. I am currently fac ...

What steps can you take to stop a tab from being inserted if one is already present?

I am facing a simple issue where I need to prevent the insertion of a tab if one already exists. Issue: I have a search bar that displays results in a div with class.result_container_2 when a user inputs a name. Upon clicking on this tab, another tab is i ...

Unlimited scrolling feature in Ionic using JSON endpoint

Trying to create an Ionic list using data from a JSON URL. JSON Code: [{"id":"1","firstName":"John", "lastName":"Doe"}, {"id":"2","firstName":"Anna", "lastName":"Smith"}, {"id":"3","firstName":"Peter", "lastName":"Jones"},{......................}] app.j ...

Implementing image rendering functionality in Vue.js

So here's what's going on: I developed a horror movie bucket list app for my bootcamp final project. The minimum viable product received positive feedback, and I obtained my certification. However, now that I've graduated, I want to enhance ...

Having trouble locating the existing placeholder in my WordPress theme that I'm trying to change

I am currently using the KuteShop WordPress Woo-commerce template and I want to customize the Placeholder Text "I'm searching for..." and "All Cate." shown in the image below: Despite my efforts, I have been unable to locate where I can make these ch ...

What is the reason that certain CSS pages are not being utilized on my website?

I am facing issues with rendering my website on a tablet device, specifically with my last 2 css pages (800px.css and 800pxland.css). Despite working fine just hours ago, now they seem to be neglected while all the other ones work perfectly. I have tried ...

Learn how to swap out the traditional "back to top" button with a customized image and make it slide onto or off the page instead of simply fading in and out

As a newcomer, I am trying to replicate a unique "back to top" effect that caught my eye on another website. Instead of the traditional fade-in approach when scrolling down, the "back to top" image in question elegantly slides out from the bottom right c ...

Place the outcome of the function into the div element's attribute

As a newcomer to HTML and JavaScript, I recently dove into using 3Dmol.js. Following a tutorial, I was able to create this code snippet that actually works: <script src="http://3Dmol.csb.pitt.edu/build/3Dmol-min.js"></script> <div id="el ...

Transitioning Between Div Elements Using Jquery

I am stuck with the following HTML code: <section> <div id="first"> ---content </div> <div id="second"> ---content </div> </section> When the page loads, the second div and its contents are not visible (I'm uns ...

Searching Text Boxes with Javascript: A Better Way to Handle Arrays

I'm struggling to implement a feature where users can search for authors in a database and be redirected to the corresponding HTML if found. Otherwise, it should display a message saying "No Author Found"... I need some assistance in getting this fun ...

Remove the innerHTML content of dynamically added elements using jQuery

After researching, it seems that event handlers are commonly added using methods such as .live(), .on(), .bind(), or .delegate(). My previous question may not have been clear, so I decided to delete it and ask a simpler one. Is there a way to clear the in ...

When a container is styled with 'overflow-y: auto', it will display additional horizontal and vertical scrolling bars

I have two files, one HTML and one CSS. The HTML file contains the following code: <div class="app"> <div class="header"></div> <div class="main"> <div class="container_1"> ...

The page fails to load when redirected, however, it briefly displays the page upon clicking the back button before navigating back to the previous page

Currently, I am working with Angular 2 and encountering an issue when attempting to click on a link. The loading bar continues to progress without displaying the data or HTML content on the page. Furthermore, if I try to go back to the previous page, the i ...

Can a mobile device be programmed to automatically bring up the keyboard for the autofocus element?

Currently utilizing Meteor for my project and facing an issue with a "Add new" button. When clicked, the button disappears and is replaced by a text box. The toggle logic between the button and input is complex and not relevant here. Check out the HTML co ...

Turn off the Antd Datepicker tooltip

I'm using Antd Datepicker in my website. We get an array of numbers representing disabled dates from an external api and show only the dates in the datepicker(no month, year etc). The date selection is for a monthly subscription and the user just sele ...

The success callback method is no longer correctly referencing the variable due to a change in the AJAX request

Imagine you have a table in your HTML file with the following rows, where {{ }} represent variables: <tr id="{{ object.id }}"> <td class="name">{{ object.name }}</td> </tr> <tr id="{{ object.id }}"> <td class="nam ...

What is the best way to adjust the size of carousel images within a box element?

How can I ensure that carousel pictures are displayed clearly within the box without overflowing? The code I tried resulted in the pictures overflowing from the box and not being visible clearly. How can I resolve this issue? .container { width: 1490px; ...

Unable to display a horizontal scroll bar

I'm having some trouble with implementing a horizontal scroll feature and can't seem to make it work. If you want to take a look, here is the fiddle Please provide me with assistance in identifying what mistakes I may be making edit Here is th ...