CSS
CSS Tricks – Centering absolute positioned elements
23 September, 2015
0

Sometime we need to centering an absolute positioned element. Maybe, You’ve already did this before. But today I’ll show you another way to centering an absolute positioned element.

Centering Vertically

<div class="outerwrap">
	<div class="innerwrap"></div>
</div>
.outerwrap { 
    position: relative;
    width: 100%;
    height: 100%;
}
.innerwrap { 
    width: 100px; 
    height: 100px; 
    background: black; 
    position: absolute; 
    top: 50%; /* or bottom */ 
    margin-top: -50px; /* always height/2 */ 
}

To determine height of an element you may use javascript/jQuery.

$(function() {
    $('.innerwrap).css('margin-left', '-' + div.outerWidth()/2 + 'px');
});


Centering Horizontally

<div class="outerwrap">
	<div class="innerwrap"></div>
</div>
.outerwrap {
	position: relative;
	width: 100%;
	height: 100%;
}

.innerwrap {
	width: 100px;
	height: 100px;
	background: black;
	position: absolute;
	left: 50%; /* or right */
	margin-left: -50px; /* always width/2 */
}

To determine width of an element you may use javascript/jQuery.

jQuery(function(){
    var div = jQuery('.innerwrap');
    jQuery(div).css('margin-left', '-' + div.outerWidth()/2 + 'px');
});
11

About author

Sabuz