2

I have a parent div and a child div. The child div has the position: absolute property. It is already centered, but I'd like to align it to the middle of the parent div. How do I go about doing that? Here's my jsFiddle

HTML

<div id='parent'>
  <div id='child'>

  </div>
</div>

CSS

#parent {
  position: relative;
  width: 500px;
  height: 300px;
  background-color: red;
}

#child {
  position: absolute;
  width: 70px;
  height: 70px;
  background-color: blue;
  left: 0;
  right: 0;
  margin: 0 auto;
  border-radius: 50%;
}
user2896120
  • 3,180
  • 4
  • 40
  • 100
  • Possible duplicate of [CSS Center text (Horizontal and Vertical) inside a DIV block](http://stackoverflow.com/questions/5703552/css-center-text-horizontal-and-vertical-inside-a-div-block) – Rob Apr 18 '17 at 19:36

3 Answers3

8

The solution is to use transform: translate(-50%, -50%) on the child div, like so:

#child {
  position: absolute;
  width: 70px;
  height: 70px;
  background-color: blue;
  left: 50%;
  top: 50%;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}

https://jsfiddle.net/jwoy7rxr/

This works because the transform positions the item based on a percentage from it's own point of origin.

Toby
  • 12,743
  • 8
  • 43
  • 75
0

Since the parent has a height based on px, you can safely use a simple margin top and bottom to centre the element.

#parent {
  position: relative;
  width: 500px;
  height: 300px;
  background-color: red;
}

#child {
  position: absolute;
  width: 70px;
  height: 70px;
  background-color: blue;
  left: 0;
  right: 0;
  margin: 115px auto;
  border-radius: 50%;
}

Here's the fiddle: https://jsfiddle.net/Lr3fLser/

penguoir
  • 155
  • 1
  • 11
0

You need to give the parent:

 #parent {
   width: 500px;
   height: 500px;
   background-color: red;
   display: table-cell;
   vertical-align: middle;
 }

 #child {
   width: 70px;
   height: 70px;
   background-color: blue;
   border-radius: 50%;
 }

You need the display table-cell in order to use the vertical-align.

Then add align="center" to the parent div's:

  <div align="center" id="parent">
    <div id='child'>

    </div>
 </div>

I have the updated JSFiddle attached:

https://jsfiddle.net/o7pzvtj3/2/

Mike Hawes
  • 555
  • 5
  • 8