Center an absolutely positioned element horizontally within a relative positioned container

Struggling to center an inner element with a position: absolute property inside of a position: relative element? Take a look at this code snippet (https://jsfiddle.net/qL0c8cau/):

html,body,div {margin:0;padding:0;}
.one {
  position: relative;
  margin: 50px auto;
  width: 200px;
  height: 100px;
  background: #900;
}
.two {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  margin: auto;
  background: #0f0;
  opacity: 0.3;
  height: 160px;
  width: 400px;
}
<div class="one">
  
  <div class="two"></div>
  
</div>

Frustrated because everything seems set up correctly, yet the alignment isn't quite right? What's the mistake in my approach?

Answer №1

Don't forget to add the following CSS code snippet:

.two {
  position: absolute;
  top:50%;
  left: 50%;
  transform:translate(-50%,-50%);
  margin: auto;
  background: #0f0;
  opacity: 0.3;
  height: 160px;
  width: 400px;
}

This piece of code ensures that the inner container will always stay centered within the outer container, regardless of their sizes.

html,body,div {margin:0;padding:0;}
.one {
  position: relative;
  margin: 50px auto;
  width: 200px;
  height: 100px;
  background: #900;
}
.two {
  position: absolute;
  top:50%;  /* this to center the box w.r.t to parent */
  left: 50%;/* this to center the box w.r.t to parent */
  /* The above two lines partially center it; the next line centers it perfectly by moving it 50% left and top internally */
  transform:translate(-50%,-50%);
  margin: auto;
  background: #0f0;
  opacity: 0.3;
  height: 160px;
  width: 400px;
}
<div class="one">
  <div class="two"></div>
</div>

Answer №2

To center a div inside .two, try using transform: translateX(-25%); instead of the traditional left and right properties. This method can be more effective when dealing with positioning issues, especially if .two is nested within .one.

Check out this JSFiddle link for reference.

.two {
  position: absolute;
  top: 0;
  bottom: 0;
  transform: translateX(-25%);
  margin: auto;
  background: #0f0;
  opacity: 0.3;
  height: 160px;
  width: 400px;
}

Answer №3

The main issue highlighted here is that the inner element (.two) has a width that exceeds its parent's width (.one). I have made some adjustments for clarity (like changing color and opacity) to demonstrate this:

*If intentionally increasing the inner element's width beyond its parent is your goal, please refer to Guatam's answer below.

html,
body,
div {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.one {
  width: 400px;
  height: 200px;
  margin: 50px auto;
  position: relative;
  background: red;
}

.two {
  height: 160px;
  width: 160px;
  margin: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  background: blue;
}
<div class="one">

  <div class="two"></div>

</div>

Answer №4

When working with a smaller px width within the nested div

You are nesting a 400px width inside a 200px width

As a result, this is why you see it displayed like that

To properly center a div, its size should be relative to the parent element

    html,body,div {margin:0;padding:0;}
    .one {
      position: relative;
      margin: 50px auto;
      width: 400px;
      height: 100px;
      background: #900;
    }
    .two {
      position: absolute;
      top: 0;
      bottom: 0;
      right: 0;
      left: 0;
      margin: auto;
      background: #0f0;
      opacity: 0.3;
      height: 160px;
      width: 200px;
    }
    <div class="one">
      
      <div class="two"></div>
      
    </div>

Answer №5

For an alternative solution to your issue, consider utilizing flex! It's a more convenient and modern approach.

Check the browser support for flex here

.wrap {
  display: flex;
  justify-content: center;
}

.one {
  display: flex;
  width: 400px;
  height: 200px;
  background: #fa0;
  justify-content: center;
  align-items: center;
}

.two {
  background: #627;
  height: 160px;
  width: 200px;
}
<div class="wrap">
  <div class="one">
    <div class="two"></div>
  </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

Preserve numerous inputs in local storage

Hope your day is going well. I've been attempting to save multiple inputs by parsing localStorage into JSON using a 'for' loop, but unfortunately, nothing is being saved. The error message in the CONSOLE reads: "Uncaught SyntaxError: Unexpe ...

Bootstrap 4 modal with scrollspy feature for a seamless full-screen experience

I am trying to implement a full-screen modal using Bootstrap 4 that incorporates a scrollspy feature for scrolling the content within the modal body. I have successfully achieved the full-screen aspect, but I am facing issues with making the content scroll ...

Encountering a blank webpage displaying a warning that reads, "The use of 'event.returnValue' is outdated

Although this issue has been discussed before and was previously considered a bug, I am currently using jQuery v1.11.0, which should have resolved it. The problem I am encountering is that when my page loads, there is supposed to be a slide-in effect (as a ...

Updating the UI in Angular for keyboard events is not working as expected

Looking to update the page based on keyboard events. I've connected the keyboard event using $window.document.onkeydown. (I understand it's not ideal, but it should still work) However, despite changing the model, I'm not seeing any updates ...

Position div at the bottom using CSS

I have been attempting to align a div at the bottom of its parent div without success. I tried the approach outlined in the following code snippet: JS Fiddle Initially, I believed that setting the CSS properties as shown below would achieve the desired r ...

Accessing administrator account through mysqli and PHP authentication

I have been working on implementing a member login feature for my website. Everything is functioning properly for regular users, but I am encountering an issue with the admin login credentials. Despite entering the correct details, I am unable to log in as ...

Struggling to remove the image tag from the jQuery ajax response

My web app is designed to send an ajax post request to a PHP script, which then returns a chunk of HTML data. This HTML includes an image and a table of information. The challenge I'm facing is how to extract the image from the rest of the HTML so tha ...

The Bootstrap navigation bar drop-down feature is not displaying the menu

After skimming through various threads on stackoverflow regarding the dropdown box in the navigation bar, none of the solutions seem to address my issue. Utilizing bootstrap version 3, I've implemented the provided navbar example from the official si ...

Exploring the wonders of CSS with Socialchef

Hey, I recently came across a solution on Stack Overflow where they provided code for SocialChef to convert decimal inputs into fractions. I'm wondering how I can write or incorporate some code to input fractions and mantissa as a fraction... I ...

Transferring information to the controller and refreshing the interface (Single-page design)

I'm stuck on a personal project and could really use some help. If anyone has any feedback, it would be greatly appreciated. Thanks in advance. In my index.php file, I have a div with the id main-container. Inside this container, there are two separa ...

Dealing with Unintended CSS Hover Effects That Just Won't Quit

I have a div that is styled as a circular shape with an image and text centered inside of it. The circle and image are visible while the text is transparent until hovered over. When hovering, the circle border flashes, the image's opacity decreases, a ...

Is there a way to show a fallback message for unsupported video file formats?

When incorporating a video element on my webpage, I typically use the following code: <video src="some source" controls> Error message </video> Based on my knowledge, the "Error message" will only appear if the browser does not support the ...

Deactivate interactive functions on the mat-slider while preserving the CSS styling

I'm attempting to create a mat-slider with a thumb label that remains visible at all times. Below is my mat-slider component: <mat-slider class="example-margin" [disabled]="false" [thumbLabel]="true" [tickInterval]="tickInterval" ...

Improving the utilization of variables in HTML

I was looking for a way to create dynamic user detail forms using a template. Each element needed to have a unique id for proper posting of details. This is what my template looks like: <div id="user-template" class="hidden"> <div class=&apos ...

"Create a dynamic and user-friendly responsive navbar using Bootstrap with toggle

I need assistance with creating a new project template to convert a WordPress template into a Bootstrap template. Currently, I am working on the navbar and facing issues with responsive design and toggle navigation. On laptop devices, the navbar looks goo ...

Currently, my goal is to create a functional copy button through the use of JavaScript

I've been attempting to create a basic copy button using JavaScript, but I keep encountering an error. TypeError: null is not an object (evaluating 'myInp.select') Whenever I click the copy button, My code looks like this: <!DOCTYPE htm ...

Display content from an external HTML page within a div using Ionic

Currently, I am facing an issue where I am utilizing [innerHtml] to populate content from an external HTML page within my Ionic app. However, instead of loading the desired HTML page, only the URL is being displayed on the screen. I do not wish to resort t ...

Determining the Size and Color of Squares in a Treemap Based on Content with D3.js

I encountered an issue with a treemap visualization. I came across an example that is similar to my situation, which can be viewed here: In the demo, you can see that the size of each square in the treemap is determined by the content size. However, all s ...

Issue with collapsed accordion toggle functionality

HTML <div class="panel-group" id="accordion"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a class="accordion-toggle" data-toggle="collapse" data ...

Adjusting the vertical dimension of an Angular 17 Material Dropdown Field?

Check out this demo where I'm exploring ways to decrease the height of the select field. Here's the code snippet: <mat-form-field appearance="outline"> <mat-label>Toppings</mat-label> <mat-select [formControl]=& ...