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

And this is the desired result that I'm aiming for

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

Automatically Scrolling Div According to its Content

Struggling to figure out how to make a parent div automatically scroll based on its child's content. I have a menu that expands when clicked and needs to scroll if the height of the child exceeds that of the parent. This is the HTML for the menu wra ...

Utilize the appendTo() function and make a switch to dynamically insert content stored in variables into a specified

I am working on developing a page with a central content div, where users have the ability to choose various options that will introduce different additional content. This added content will then present more opportunities for adding new elements, ultimate ...

Stripping away HTML tags from a JSON output

I'm attempting to retrieve a JSON result using jQuery. $.ajax({ type: "GET", url: "http://localhost:8080/App/QueryString.jsp?Query="+query, contentType:"text/html; charset=utf-8", dataType: "json", success: function(json) { if(data!="") ...

Tips to store Google fonts in the assets directory

I've included this link in my styles.scss @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap'); While it works locally, the API fails on production or is blocked. How can I host it within my p ...

What is the most efficient way to calculate the total sum of all product amounts without using Jquery?

I am working with a dynamic table where data is inserted and the total of each product is calculated by multiplying the price by the quantity. What I need now is to get the sum of all the totals for each product. You can see how the table looks here: htt ...

How to dynamically reduce the number of columns in a textarea using jQuery according to its content

Does anyone know how to make a textarea shrinkwrap the text inside on blur? The default number of columns is 10 or 15 and I want the textarea to adjust its width based on the text content. I have tried the following code: $('textarea').on(&apos ...

Using CSS to Create a Background with RGBA Color and Image

Having an issue with my CSS. I'm trying to create a scrolling background for the left section of my website. The RGBA is currently overlapping the entire page, but I only want it to overlap the background image. The same goes for the gridtile (the ov ...

Develop a website using HTML and CSS for the front-end design, complemented by Java for the

I find myself at a standstill with a project I want to tackle, but unfortunately, my knowledge of modern web development, particularly full stack, is minimal. As a result, I am completely clueless on how to proceed. Here is what I am familiar with and what ...

Stuck with the same icon even after a successful AJAX call

I am currently working on implementing a 'add to my list' function in my web app. The goal is to change the color of an icon when a user clicks on it, after sending the necessary data to the server. Despite successfully sending the data to the s ...

Checking all checkboxes in a list using Angular 5: A simple guide

I have a list that includes a checkbox for each item, and I want to confirm if all of them are checked off. This is the HTML code snippet: <ul class="ingredient-list" > <li class="btn-list" *ngFor="let ingredient of recipe.ingredients"> ...

Revealing information about a photo when hovering over it

I am currently working on a project where I need to display images from a database in two columns. My goal is to have additional details about each image, such as the country and year it was taken, appear when I hover over them. A good example of what I&ap ...

Encountered issue while converting half of the string array to JSON using JavaScript

I encountered an issue with the code below while trying to convert an array into JSON. Here is my code: <html> <head> </head> <body style="text-align:center;" id="body"> <p id="GFG_UP1" style="font-size: 16px;"> </p ...

Having trouble with the move_uploaded_file function in PHP?

I have been actively studying PHP and am currently working on a CMS project. I have encountered an issue with image uploading. PHP if ( $_POST['img']) $uploads_dir = '/images'; $tmp_name = $_FILES["img"]["tmp_name"]; $name = $_FIL ...

Strange spacing below body element discovered while browsing website in Firefox 7

Currently, I am facing an issue on my website in Firefox 7. A margin is causing the gradient in #wrapper to shift upwards from the bottom, disrupting the layout. Despite resetting the margin to 0 on body and html, I am unable to pinpoint the root of the pr ...

Using jQuery to create radial-gradients with the background-css feature

I'm a newcomer to this online community and English is not my first language. Despite that, I will do my utmost to clearly explain the issue at hand. Recently, I utilized the .css function in jQuery to create a design element successfully. However, I ...

Tips for disabling scrolling on a <div> using another <div> as a lock

I am facing an issue with a page where a div is appended to the body of an HTML. The problem is that there are two scrolls appearing - one on the new overlaying div and another behind it. Here is an approximate structure of the page, how can I ensure that ...

Integrate SVG into the dropdown menu without duplicating the SVG element

I have an SVG of a right arrow: <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000"> <path d="M0 0h24v24H0V0z" fill="none"/> ...

The magic of CSS Pseudo-classes in Inline Styling

For the longest time, I've been under the impression that you cannot include in-line :hover{..} styles to an element. However, recently I stumbled upon this page which showcased examples like this. <a href="http://www.w3.org/" s ...

Selenium - How to pass a file path to a dynamically generated input element that is not visible in the DOM

Check out this example of HTML code: This is how you create a visible button and display the selected file: <button id="visible-btn">visible button</button> <p>selected file is: <span id="selected-file"></spa ...

How come my TABLE element is not showing padding when using border-spacing?

Looking to add some padding above and below my TABLE element, I came across the border-spacing property. Here's my table: <table id="ranks"> <tbody><tr class="ranksHeaderRow"> <th></th> <th>Name ...