What is the best way to horizontally center a div while ensuring the content within the div stays aligned?

I'm attempting to align a div in the center while maintaining the position of its contents.

Check out my code snippet:

<style>
  .wrap{
    position: relative;
  }

  .character{
    position: absolute;
    bottom: -10%;
    left: 0;
    height: 100px;
  }
</style>

<div class="wrap">
  <img class="background" src="https://p4.wallpaperbetter.com/wallpaper/348/300/844/digital-digital-art-artwork-planet-fantasy-art-hd-wallpaper-preview.jpg">
  <img class="character" src="https://lh3.googleusercontent.com/KWjPQjV1ZZXvMBFNjab-HK3ZHTO5zSpkPTFf3x-d87RNBMnZ3A2hCbTZNumHxfydGQ">
</div>

Here's the outcome I'm currently seeing https://i.sstatic.net/Dr5xF.png

And this is the desired result that I'm aiming for https://i.sstatic.net/PSDHR.png

Answer №2

.wrap {
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0)
}

.character {
  position: absolute;
  bottom: -10%;
  left: 0;
  height: 100px;
}
<div class="wrap">
  <img class="background" src="https://p4.wallpaperbetter.com/wallpaper/348/300/844/digital-digital-art-artwork-planet-fantasy-art-hd-wallpaper-preview.jpg">
  <img class="character" src="https://lh3.googleusercontent.com/KWjPQjV1ZZXvMBFNjab-HK3ZHTO5zSpkPTFf3x-d87RNBMnZ3A2hCbTZNumHxfydGQ">
</div>

Answer №3

One creative way to center a div is by adding an additional container with a wrap class that helps in achieving alignment along with responsiveness. The key is to use the extra container as a containment for the wrap class, and then align it at the center.

Give it a try next time!

Margin: 50px auto; This method can also center elements within the body, although it may not work effectively in all scenarios.

.container{
     display: flex;
     align-items: center;
     justify-content: center;
}
                  
.wrap{
    display: inline-block;
    position: relative;
}
.character{
     position: absolute;
     bottom: -10%;
     left: 0;
     height: 100px;
}
<div class="container">
        <div class="wrap">
          <img class="background" src="https://p4.wallpaperbetter.com/wallpaper/348/300/844/digital-digital-art-artwork-planet-fantasy-art-hd-wallpaper-preview.jpg">
          <img class="character" src="https://lh3.googleusercontent.com/KWjPQjV1ZZXvMBFNjab-HK3ZHTO5zSpkPTFf3x-d87RNBMnZ3A2hCbTZNumHxfydGQ">
        </div>
      </div>

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

What is the best way to locate the final text node within the <p> element?

Looking at the code below, my goal is to identify and retrieve the text node that serves as the last child element. <p class="western" style="margin-bottom: 0.14in"> <font color="#000000"> <font face="Arial, serif"> <font ...

Is there a way to insert an attribute in HTML without simply appending it to the end of the tag?

I've been working on incorporating the code snippet below that I found in an angularjs table sort function. In the code, you can see the ts attributes being added to the html. However, this method is not suitable for hosting on Salesforce. Can anyone ...

I seem to be having trouble properly sizing the width of my forms in Mui React

Having trouble with the sizing of my tabs in a project I'm working on. The first tab displays ingredients, while the second tab allows for adding new ingredients with various forms. However, when selecting different forms, the width of the form contai ...

Utilize OpenLayer3 to showcase Markers and Popups on your map

I am currently exploring how to show markers/popups on an osm map using openlayers3. While I have come across some examples on the ol3 webpage, I'm interested in finding more examples for coding markers/popups with javascript or jquery, similar to som ...

Customize the appearance of polygons in OpenLayers 2 by adjusting the fill color and opacity

I am aiming to use different fill colors and opacity values for various shapes (such as Triangle, Circle, Square, Hexagon, etc.). Although I can draw the shapes, set different titles, and stroke colors with the code below, I'm struggling to define th ...

Create a fresh array by merging two existing arrays while maintaining the order of values

I have a pair of arrays: array one: ( [0] => 2 [1] => 5 ) array two: ( [0] => Sentry [1] => Maxima ) and I'm attempting to create a new array that resembles the following new array: ( ["Sentry"] => 2 ["Maxima ...

Issue with ThreeJs: Difficulty loading separate images on top and bottom surfaces

I've been trying to place different textures on the top and bottom sides using Threejs to display unique images on each side. However, I'm encountering an issue where the same image is being displayed on both the top and bottom sides. Below is th ...

Utilizing graphics within the Atom text editor

Hey, I have a bit of a silly question. I can't seem to figure out why these images aren't showing up on my Atom editor. Can anyone help me with this? <body> <div class="top-container"> <img src="images/clou ...

Designing an image transformation page by segmenting the image into fragments

Does anyone have insight into the creation process of websites like this one? Are there any plugins or tools that can assist in building something similar? ...

Having trouble integrating Bootstrap with Fullpage.js

After following this solution, I attempted to create a basic full-page layout using bootstrap. I aim to have a front end that scrolls like a full page, ensuring responsiveness. Folder Setup https://i.sstatic.net/ylZF8.png Code Snippet <!DOCTYPE htm ...

Color picker can be utilized as an HTML input element by following these steps

After trying out various color pickers, I was not satisfied with their performance until I stumbled upon Spectrum - The No Hassle jQuery Colorpicker. It perfectly met my requirements. <html> <head> <meta http-equiv="content-type" content="t ...

Troubleshooting JavaScript's onchange Function Dysfunction

Here is the code snippet I am working with: <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> <script src="jquery-2.2.1.min.js"></script> <script src="slike.js"></script> ...

Tips for preventing the state of a checkbox from being saved in the browsing history

I have implemented a mobile menu using a checkbox, with the following simplified code: input, ul { display: none; } label { cursor: pointer; } input:checked ~ ul { display: block; } <input type="checkbox" id="toggle-menu" /> <label for="t ...

Tips for organizing CSS styles into common and unique statements

Is there a way to apply the same background style but different font styles to two elements without duplicating the style statement in the header part? ...

Eliminate any excess space to the right of the image

Utilizing Bootstrap alongside React, I've encountered an issue with images causing unwanted whitespace to the right. I've thoroughly examined the elements but have been unable to resolve this issue. Despite researching Bootstrap Col online, the ...

The process of loading and saving extensive data to the local storage of a user's Firefox browser involves extensive reading and writing operations

Our team has developed a sophisticated HTML5 offline application that houses a substantial amount of data, totaling tens of megabytes. We are looking for a way to allow users to save and retrieve copies of this data on their disk. While we have made some ...

Achieving Flexbox alignment in a responsive layout

Struggling with achieving a responsive layout using Flexbox. Picture a page filled with panels. The main objective is to display a certain number of panels per row, aligned both horizontally and vertically like the rest. The main issue I am encountering ...

Unable to change background image using jQuery

Snippet: const imageUrl = 'img/star.png'; $("#venueId-"+nodeId).css('background','url("'+imageUrl+'") no-repeat top right'); This piece of code is the start of a function that triggers upon clicking. The goal is to ...

Develop an ASCX component to handle various tasks

I am currently in the process of developing a unique custom control that will feature two radio buttons. This project is being carried out using MVC4 and ASP.NET technology. At the moment, I have successfully created two sets of two radio buttons on separa ...

Having Trouble with Jquery Toggle Function!

I have put together a small Jquery script after much contemplation (since I am new to this), and unfortunately, it is not working as expected! Here's the issue: in my code, I want to click on an element defined by the variable trigger, and when clicke ...