0

I'm centering a div inside another div using percentage margins. I do this because the parent div is going to change sizes based on browser size.

See this jsfiddle for a demo.

My CSS:

#test-wrap {
    position: absolute;
    width: 400px;
    height: 250px;
    background-color: pink;
}

.white-wrap {
    position: absolute;
    width: 50%;
    height: 50%;
    background-color: white;
    left: 50%; margin-left: -25%;
    top: 50%; margin-top: -25%;
}

This works fine in Safari, but in Chrome the child div is appearing higher than it should.

Perhaps there's a better way to achieve such a thing, that works on all browsers and doesn't rely on pixel margins? Any suggestions would be greatly appreciated!

Jeroen
  • 60,696
  • 40
  • 206
  • 339
user1374796
  • 1,544
  • 13
  • 46
  • 76

4 Answers4

2

You should use the attribute margin. So your CSS of white-wrap should be:

.white-wrap {
    position: relative;
    margin: 0 auto;
    width: 50%;
    height: 50%;
    background-color: white;
}
Balibia
  • 49
  • 2
0

Try

#test-wrap {
   display: table-cell;
    width: 500px;
    height: 500px;
    background: gray;
    vertical-align: middle;
    text-align: center;
}

.white-wrap {
     display: inline-block;
    width: 200px;
    height: 200px;
    background: red;
}
Arun Bertil
  • 4,598
  • 4
  • 33
  • 59
  • this is a nice solution, centering text horizontally inside the `.white-wrap` might be a bit tricky though: http://jsfiddle.net/neal_fletcher/bNXww/23/ ? – user1374796 Jul 19 '13 at 09:03
  • sorry I meant to say 'vertically', centering the text inside `.white-wrap` vertically may be quite tricky – user1374796 Jul 19 '13 at 09:14
0

This is my favorite way to accomplish this (works in all modern browsers and IE8+).

<style>
/* Can be any width and height */
.block {
  height:500px;
  text-align: center;
}

/* The ghost, nudged to maintain perfect centering */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can be any width or height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}
</style>

<div class="block"><div class="centered">Centered Content</div></div>

And here is a jsFiddle that mimics your example.

Justin
  • 26,443
  • 16
  • 111
  • 128
  • nice, very nice! Although, the `.block` div is 300px inside the 500px parent, I was hoping the child div would be a percentage of it's parent, if at all possible? – user1374796 Jul 19 '13 at 09:09
0

You should set those properties too :

* {
  box-sizing:                 border-box;
  -moz-box-sizing:            border-box; /* Firefox */
  -webkit-box-sizing:         border-box; /* Safari */
}

Once you defined a size for a DIV or anything else, the margin, padding and everything will be in the sizing and won't increase the size.

Juaniyyoo
  • 87
  • 5