Code snippet to center an image within a div using background-position in CSS

<div class="divOverlay">
  <div class="div-overlay-content" >
    <div class="pointer" ></div>
  </div>
</div>

I have a unique layout where there is a div with a background image and a pointer that remains centered. The challenge lies in dynamically moving the background image to different positions by adjusting the specified properties.

background-position: 0% 0%;

For instance, setting it to 50% 50% aligns the center of the image with the central pointer. However, I am seeking a solution for corner scenarios where values like 0% 0% should position the top left corner of the image at the center with white space around it.

Is there a way to achieve this using CSS alone, without altering the actual image by adding additional whitespace?

Visit this link for a live demo on jsfiddle https://jsfiddle.net/mkd914gf/21/

Below is the relevant CSS code:

.divOverlay {
    height: 200px;
    width: 200px;
    position: fixed;
    z-index: 1;
    bottom: 0;
    left: 0;
    overflow-x: hidden;
 }

.div-overlay-content{
   height: 100%;
   width: 100%;
   background-image: url(https://topdrawer.aamt.edu.au/var/aamt/storage/images/media/tdt/patterns/p_gt_t3_e1_a1_fig1/278788-1-eng-AU/P_GT_T3_E1_A1_fig1.jpg);
   background-position: 0% 0%;
}

.pointer {
   left: 50%;
   top: 50%;
   background-color: red;
   position: absolute;
   width: 10px;
   height: 10px;
   background-size: contain;
   background-repeat: no-repeat;
}

Answer №1

If you're looking to achieve this effect, there are a few different approaches you can take. Some people like to use the ::before and ::after pseudos, while others prefer using the background-attachment property (although keep in mind this only works with <img> tags, not background images).

Personally, I find it easier to position the entire div absolutely. So, you would have an absolute positioned div inside a relative positioned parent element. You can set the height and width of each element, add a background image with background-size, and hide any overflow using overflow: hidden. Then, simply use top, right, bottom, and left properties to position the div containing the image.

I also included a simple method for centering the red dot that takes into consideration its size.

Feel free to check out the code on this fiddle: https://jsfiddle.net/9sp2te4o/1/

HTML

<html>
  <body>
    
    <div class="divOverlay">
      <div class="div-overlay-content" ></div>
       <div class="pointer" ></div>
    </div>
    
  </body>
</html>

CSS

.divOverlay {
  height: 200px;
  width: 200px;
  position: fixed;
  z-index: 1;
  bottom: 0;
  left: 0;
  overflow:hidden;  /* Keep content hidden outside the box */
  position:relative;  /* Ensure children stay within this container */
  background-color:rgba(255, 0, 0, 0.5);
  margin:10px;
}

.div-overlay-content{
  position:absolute; /* Position this element absolutely */
  height: 100%;
  width: 100%;
  background-size:cover; /* Cover the entire area */
  left: -25%; /* Adjust position for image */
  top: -25%; /* Adjust position for image */
  
  background-image: url(https://topdrawer.aamt.edu.au/var/aamt/storage/images/media/tdt/patterns/p_gt_t3_e1_a1_fig1/278788-1-eng-AU/P_GT_T3_E1_A1_fig1.jpg);
}

.pointer {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);  /* Center while considering dimensions */
  height:10px;
  width:10px;
  background-color:red;
    
}

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

Expand the dimensions of the bootstrap navigation bar

Is there a way to expand the Bootstrap nav bar to fill the entire screen? Currently, it only occupies half the screen in desktop view, but it is working fine in mobile optimization. <body> <nav class="navbar navbar-expand-lg navbar-light bg-lig ...

Problem with input placeholder when using text transformation

I recently created an input form and applied the CSS property text-transform: uppercase; #textbox { outline:none; background:#732ab7; caret-color:lightgreen; border-style:groove; border-width:0px 0px 10px 0px; border-top:none; ...

Incorporating groovy script into HTML: Is it possible, akin to embedding JavaScript

Can groovy script be embedded in HTML similar to JavaScript? I am interested in creating an onclick button event that utilizes groovy script instead of JavaScript. Thank you. ...

Angular and JS do not have the functionality to toggle the split button

I have a question that seems similar to others I've seen, but I haven't found a solution yet. Can someone please review my code? In the component, I have {{$ctrl.init}} and {{$ctrl.people}} assigned. I am sure this assignment is correct because ...

Styling with CSS based on the remaining width of the viewport relative to the height

If you're viewing this on a tablet browser, the dimensions are set relative to the viewport width and height. Let's assume a landscape orientation for simplicity. Inside a fullscreen container, there are two divs positioned absolutely, just like ...

The preselected value in an AngularJS select box is set to static HTML by

In my HTML, I have a select tag that I am populating using ng-repeat. <td> <select ng-model="item.data.region" style="margin-bottom: 2px;"> <option ng-repeat="region in vm.regions track by $index" value="{{region}}">{{region} ...

Having trouble with the numbering system - any suggestions on how to resolve this issue?

I am experiencing an issue with numbering a list .content ol { padding-left: 0px; counter-reset: item; } .content ol > li { display: block; } .content ol > li::before { content: counters(item, ". ") " " ; counter-increment: ...

The Next.js application is unable to load the combined CSS from a React Component Toolkit

My React components repository includes individual .css files for each component which are imported into the respective components. These components are then bundled using a rollup configuration and published as an NPM package, with all component CSS being ...

Issue with jquery curvy corners not functioning properly on Internet Explorer 8

Check out my website at If you view the page in IE8 and then in IE7 compatibility mode, you'll notice a strange issue. The box on the right disappears in IE8 but displays perfectly rounded corners in IE7. I am currently using the jQuery Curvy Corner ...

Display data-content vertically using CSS

Looking for a way to display text vertically one by one with CSS? While the rotation method produces this result: https://i.stack.imgur.com/utAiN.png However, I aim to achieve something more like this: https://i.stack.imgur.com/fuVyb.png If you have an ...

Angular5 Carousel: Spinning Your Web Pages in Style

I am in the process of creating an angular carousel slide. I found the necessary HTML and CSS code from the Bootstrap carousel example, but I am struggling with the JavaScript implementation from the site. Below is the HTML code in my app.component.html: ...

How is the height and width of the header determined?

When examining the theme by clicking "inspect element" on the green portion (<header> ), you will notice that the height and width properties have pixel values that change dynamically as the window is resized. So, where do these values originate fr ...

Receiving an absence of string or a null value from a text box

My goal is to test the functionality of an <input> element by entering text into a textbox and then displaying that data in the console. However, I am encountering issues with retrieving and printing the content. Additionally, I am interested in test ...

Please insert a border shade on my navigation bar

I have been attempting to add a special effect to my menu. Specifically, I have been trying to include a 3px border at the top of each "li" element in my menu that only appears when hovered over. Unfortunately, my attempts using :after pseudo-selector hav ...

jQuery live DataAttribute manipulation

Here is the code snippet I am working with: <head runat="server"> <title>Sidebar</title> <link href="css/style.css" rel="stylesheet" /> <script src="scripts/jquery-1.11.1.min.js"></script> <script src ...

What are the steps to retrieve dynamic text values using Alpine.js?

<script defer src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f1909d81989f94b82b1c2df89e089">[email protected]</a>/dist/cdn.min.js"></script> <p @click="printThisTextToSpan"&g ...

Value of MySQL in a web form

Currently in my PHP code, I have the following: echo '<input type="email" name="email" value=''; I am looking to automatically populate the value with a data from a MySQL row (let's say ['name']), but I am encountering syn ...

What could be causing certain Bootstrap classes and CSS properties to not function properly in my code?

My goal was to create a website template using BOOTSTRAP and CSS. However, I encountered some issues in my code where certain Bootstrap classes are not functioning as expected, such as lead, font-weight, color, bg-color, etc. I noticed that if I apply a Bo ...

Inserting cards into an HTML document using JavaScript

I have a situation where I need to display 3 cards in a row instead of stacking them vertically. How can I achieve this? arr = [{ "Name": "Peter", "Job": "Programmer" }, { "Name": "John", "Job": "Programmer" }, { "Name": "Kev ...

Extract data from the HTML source code in JavaScript and transfer it to a personalized JavaScript variable within Google Tag Manager

Running an e-commerce website on Prestashop and facing an issue with data layer set up. Instead of a standard data layer, the platform generates a javascript variable called MBG for Enhanced E-Commerce implementation. <script type="text/javascript"> ...