Center the background image at the halfway mark on the screen

Can someone help me figure out how to position an image so that it appears exactly at the halfway point of the screen?

I've researched different ways to position images within a div, but I'm struggling with positioning it on the entire screen.

I've experimented with using position: absolute;, background-position, and other CSS styles without success.

Percentages don't seem to work as expected because the image moves when the screen is resized, not staying fixed on its vertical axis.

.background {
  position: absolute;
  top: 10px;
  left: 50%;
  width: 50%;
  height: 250px;
  background-image: url('https://www.google.com/logos/doodles/2020/december-holidays-days-2-30-6753651837108830.3-law.gif');
  background-position: 0 0;
  background-repeat: no-repeat;
  background-size: cover;
}
<html>

<body>
  <div class="background">
  </div>
</body>

</html>

Answer №1

Using the background property is not giving you the desired result.

Allow me to show you how it can be done:

CSS & HTML:

    .background {

      width: 50%;
      margin-right: 25%;
      float: right;
      height: 500px;
      text-align: center;;

    }
    img{
        width: 100%
    }
<html>

    <body>
      <div class="background">
        <img src="https://www.google.com/logos/doodles/2020/december-holidays-days-2-30-6753651837108830.3-law.gif">
      </div>
    </body>

</html>

Answer №2

Effective Solution

The most commonly used and straightforward method for centering a div on the screen or within its parent is to apply margin: 0 auto;. This shorthand property sets the top and bottom margins to zero and the left and right margins to auto.

.background {
  margin: 0 auto;
  width: 50%;
  height: 250px;
  background-image: url('https://www.google.com/logos/doodles/2020/december-holidays-days-2-30-6753651837108830.3-law.gif');
  background-position: 0 0;
  background-repeat: no-repeat;
  background-size: cover;
}
<body>
  <div class="background">
  </div>
</body>

Alternative Fix (Not recommended)

If the div you wish to center has a fixed width and height, you can opt for absolute positioning as shown below.

#center {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -100px;
    width: 200px;
    height: 100px;
    background-color: #111314;
}
<div id='center'></div>

Another Approach

Using Flexbox offers a responsive solution for centering elements. Simply set the parent container with display: flex and use justify-content: center; to align items horizontally and align-items: center; vertically.

html,body {
  height: 100%;
}

.parent {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.center {
  background-color: #112341;
  width: 100px;
  height: 100px;
}
<div class="parent">
  <div class="center"></div>
</div>

Answer №3

My solution was to set the background element to have a position:fixed property and then adjust the width to be 200%. This approach consistently kept the image centered on the screen, regardless of the screen's width.

.background {
  position: fixed;
  background-position-x: center;
  background-position-y: center;
  background-repeat: no-repeat;
  background-size: contain;
  background-image: url('https://marketing.dcassetcdn.com/blog/30-Famous-Triangle-Logos/google-drive-logo.jpeg');
  height: 75%;
  width: 200%;
}
<html>

<body>
  <div class="background">
  </div>
</body>

</html>

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

Navigate through input fields while they are hidden from view

Picture this scenario: <div> <input tabindex="1"> </div> <div style="display:none"> <input tabindex="2"> </div> <div> <input tabindex="3"> </div> As I attempt to tab through these input f ...

Exhibition: Sequential Images Transition Using JQuery

Hey there! I've been experimenting with fading images in and out of this gallery. I tried using the following code: $('#slides').fadeTo(3000, 0.0); If you want to check it out, here's a link to my pen: https://codepen.io/anon/pen/gwRX ...

Achieving consistent alignment for text on a curved path

I am working on a unique "flow-builder" project and I need to achieve this specific result: https://i.sstatic.net/6TTuS.png At the moment, my current edge looks like this: https://i.sstatic.net/9ydzx.png The text on the edge is currently aligned with the ...

Having trouble getting CSS3 Keyframes to function properly?

Check out the following code snippet: .startanimation { height: 100px; width: 100px; background: yellow; -webkit-animation: animate 1s infinite; } @-webkit-keyframes animate { 100% { width: 300px; height: 300px; } ...

Google has not detected any hreflang return tag

My website has encountered indexing errors on Google Search Console. According to the reports, many pages are showing an alternate version in a different language without the "return tag". This "return tag" is believed to be the pointer back to the origina ...

What criteria do browsers follow to determine the specific colors to use for border styles like inset and outset?

When I set border: 1px outset blue; as the style for an element, the browser displays two distinct border colors: one for the top and left borders, and another for the bottom and right borders. li { border: 10px outset #0000FF; color: #FFF; ...

Horizontal scrolling alone is proving to be ineffective

My current HTML code includes a table that is integrated with PHP Laravel. The data is being pulled from Admin.php to populate the table, resulting in it being wider than the screen window. To address this, I added a horizontal scroll bar for navigation pu ...

In IE9/10, the absolutely positioned pseudo element within a table cell does not fully overlay its parent

My layout includes nested div elements displayed as a table and table-cell, with each cell containing an absolutely positioned :before element that covers the entire cell. While this setup works perfectly in most browsers, I am facing an issue in IE9, 10, ...

Disabling the ESC key from clearing input fields in Bootstrap-5: A step-by-step guide

I have come across this code snippet for a search field: <form class="container" role="search"> <div class="row"> <div class="col-12"> <input name="searchItem" #search ...

Converting XML hierarchy into a flat HTML table using XSLT

Looking for a way to transform hierarchical XML into an HTML table? Here's the challenge: <node text="a" value="1"> <node text="gga" value="5"> <node text="dh" value="9"> <node text="tyfg" value="4"> < ...

Tips for deleting a CSS class from a Wicket element

If you're looking to dynamically update a CSS class of a component in Java code, one way to do so is by using an AttributeAppender: component.add(new AttributeAppender("class", true, new Model<String>("foo"), " ")); You can also utilize a util ...

The element residing within the body exceeds the body's dimensions

HTML : <body> <header> <div> </div> </header> </body> CSS : body { width : 1000px ; } header { width : 100% ; } If these codes are implemented, The header's width should be the same as the body's ...

Tips on adjusting the font size of headers in a Vuetify v-data-table?

I've been struggling to change the font size of the headers in my v-data-table. No matter what I try, the font doesn't seem to update. I even experimented with the Chrome developer tool and managed to make it work there. However, when I attempt t ...

Issue encountered when submitting form: Error identified as "Unexpected string expression without template curly in string"

As a novice in React.js, I am facing an issue where setState is not functioning properly when submitting a form. Any suggestions on how to resolve this problem? > class Home extends Component{ constructor(props){ > super(props) > ...

How can I achieve rounded corners in Internet Explorer using JQuery?

I've tried using various plugins like curvycorners, DD_roundies, and behavior: url(ie-css3.htc);, but none of them seem to work properly. Can anyone suggest alternative methods for achieving rounded corners in IE? My website is designed to be resizabl ...

Incorporating Angular module into the mean.io bundle

Need help with adding the angular-ui-grid module to a mean.io package: $ cd packages/custom/mypackage $ npm install angular-ui-grid --save To import the JS, add this line to packages/custom/mypackage/public/index.js: import 'angular-ui-grid'; ...

Apply a style to the div element that contains a TextInput component

As a beginner in the world of React and Material UI, I am currently working with Material UI version "1.0.0-beta.17", React 15.6.2, styled-components 2.0.0, and styled-components-breakpoint 1.0.1. Within a div element, I have two TextInput fields. const ...

Is it possible to set all UI forms to a readonly/disable mode?

We have a specific requirement where, if the user's access level is set to "READ ONLY", all form input elements should be made readonly. Our coding approach involves using a template HTML that contains widgets which are referenced in the correspondin ...

How can the "Search within page" feature locate words that are divided between different elements?

I need to present text in groups of a specific length while still being able to search for text that spans multiple groups on the page. Additionally, I want to include a character above each group. My current approach is as follows: body { marg ...

What is the reason behind the browser not reusing the authorization headers following an authenticated XMLHttpRequest?

As I work on developing a Single Page Application using Angular, I have encountered an interesting challenge. The backend system exposes REST services that require Basic authentication. Surprisingly, while obtaining index.html or any of the scripts does no ...