0

I'm trying to center a div horizontally and vertically inside another div. My problem is that on window resize the width and height of parent div changes. For that, I have problems to center the div in the center of the parent div. Here is a case where I the width and height of the parent div is defined:

<div id="parent" style="">  
  <div id="child">Foo foo</div>
</div>

And the ccs:

#child {
  display: table;
  position: absolute;
  margin: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color:red;
  width:50px; 
  height:50px
}
#parent{
  background-color:blue;
  width:400px; 
  height:400px;
}

I don't know why it's so difficult to achieve it? JSFIDDLE

Ritchie
  • 73
  • 1
  • 8

5 Answers5

1

here's one way to achieve it :)

https://jsfiddle.net/e4xhrvcf/

.parent{
  width:500px;
  height: 500px;
  background-color:red;
  display: flex;
  align-items: center;
}
Lulceltech
  • 1,662
  • 11
  • 22
0

Use CSS-Flexboxes by setting display: flex; for the parent div, and setting margin: auto for the child div.
remove the top,bottom,right,left from the css.

Syntac
  • 1,687
  • 11
  • 10
0

If I understood what you want, I think you just need to add relative position to the parent in order to get absolute in the child to work:

#parent{
 background-color:blue;
 width:400px; 
 height:400px;
 position : relative;
}
Sergeon
  • 6,638
  • 2
  • 23
  • 43
0

http://codepen.io/anon/pen/rrdVbO

#parent{
  position: relative;
  background-color:blue;
  width:400px; 
  height:400px;
}
#child {
  position: absolute;
  top: 50%;
  left: 50%;
  background-color:red;
  width:50px; 
  height:50px;
  transform: translate(-50%, -50%);
}

The parent needs to have a position definition for the child's absolute to work. Use top and left 50% to center the left top corner of the child and transform: translate(-50%, -50%) to move it back up and left by half of its own height and width.

Johannes
  • 64,305
  • 18
  • 73
  • 130
0

try this,

HTML

<div id="grandParent">
  <div id="parent">
    <div id="child">
    foo foo
    </div>
  </div>
</div>

CSS

html, body{
  height:100%;
}

#grandParent{
  display: table;
  min-height:100%;
  width:100%;
}

#parent{
 background-color:red;
 display:table-cell;
 text-align: center;
 vertical-align:middle;
}

#child {
 background-color:blue;
 display:table;
 margin:0 auto;
}

Fiddle

https://jsfiddle.net/guruling/7o764szj/2/
Guruling Kumbhar
  • 1,039
  • 1
  • 8
  • 18