css - Centering div using percentage margins -


i'm centering div inside div using percentage margins. because parent div going change sizes based on browser size.

see this jsfiddle 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, in chrome child div appearing higher should.

perhaps there's better way achieve such thing, works on browsers , doesn't rely on pixel margins? suggestions appreciated!

this favorite way accomplish (works in modern browsers , ie8+).

<style> /* can width , height */ .block {   height:500px;   text-align: center; }  /* ghost, nudged maintain perfect centering */ .block:before {   content: '';   display: inline-block;   height: 100%;   vertical-align: middle;   margin-right: -0.25em; /* adjusts spacing */ }  /* element centered, can 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 jsfiddle mimics example.


Comments