1

Good day.

I know that if you want to absolute center a div, you do this:

<div id="parent">
   <div id="child">blahblah</div>
</div>

CSS:

#parent{
   width: 500px;
   height: 500px;
   position: absolute; /*(or relative)*/
   top: 50%;
   left: 50%;
   margin-top: -250px;
   margin-left: -250px;
   text-align: center;
}

What if the parent div is a fluid div? How do you ABSOLUTE center it meaning:

#parent{
  max-width: 500px;
  max-height: 500px;
  top: 50%; ->is this right?
  left: 50%; -> is this right?
  margin-top: ???;
  margin-left: ???;
  text-align: center;
}
David Van Staden
  • 1,739
  • 9
  • 34
  • 52

3 Answers3

0

As the width and height are fluid, you need to go with javascript or jQuery. Just add the below code in head tag. (The below example is in javascript)

<script>
   window.onresize = function(){
      //To work even on resize
      getToMiddle();
   }
   window.onload = function(){
      getToMiddle();
   }

   function getToMiddle(){
      var box = document.getElementById('parent');
      var height = box.offsetHeight;
      var width = box.offsetWidth;
      box.style.top = -(height/2);
      box.style.left = -(width/2);
   }
</script>

and your css would be something like this:

#parent{
   max-width: 500px;
   max-height: 500px;
   background-color:green;
   position:absolute;
   top: 50%;
   left: 50%;
  /* width: 10%;
   height: 10%; */
}

To test, give width: 10%; and height: 10%

Working Fiddle

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
  • Thanks but in your fiddle only the width resizes, only the height...and the text inside the box is not contained inside when resizing... – David Van Staden Mar 10 '13 at 15:57
  • @DavidVanStaden Give also `min-width` and `min-height`. Something like this in this fiddle http://jsbin.com/ewizad/10/edit – Mr_Green Mar 11 '13 at 03:37
0

This can be done with CSS alone.

#parent {
  position: absolute;
  max-width: 500px;
  max-height: 500px;
  width: 100%;
  height: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

See demo https://jsfiddle.net/matharden/8kmvt8qd/

matharden
  • 757
  • 6
  • 15
0

I'll simply use flex to achieve this...

#parent {
  display: flex;
  justify-content: center;
}
<div id="parent">
  <div id="child">blahblah</div>
</div>
Pranesh Ravi
  • 18,642
  • 9
  • 46
  • 70