Centering a div with CSS without negative margin or jQuery
You know, centering a div is always a pain in the ass, but now we have the cure, we have the pill, we have the suppository. The most note workaround was to use negative margin or using jQuery but with the CSS translate
property you can do it simpler.
LESS-CSS translate solution
Here is a LESS CSS class for horizontal centering (vertical and vertical+horizontal centering need little changes that you will able to do if you’re here):
// Apply this class to the HTML element you want to horizontal center
.hcenter {
position: absolute;
left: 50%;
.translate(-50%; 0%); // Bootstrap 3 mixin
}
If you don’t use Bootstrap also add this class (taken from Bootstrap mixins) to get it works:
.translate(@x; @y) {
-webkit-transform: translate(@x, @y);
-ms-transform: translate(@x, @y); // IE9 only
transform: translate(@x, @y);
}
jQuery solution
If you prefer a jQuery solution you can check this post, or use the below function I created for horizontal centering each elements with .hcenter
class.
Notice: this function centers the element relatively to the parent element.
Coffeescript version
# Function: horizontal centering of elements with .hcenter class
hCenter = ->
$(".hcenter").css
position: "absolute"
marginLeft: ($(".hcenter").parent().width() - $(".hcenter").outerWidth()) / 2
return
# Centers .hcenter elements on window resize
$(window).resize hCenter()
hCenter()
Javascript version
var hCenter;
hCenter = function() {
$(".hcenter").css({
position: "absolute",
marginLeft: ($(".hcenter").parent().width() - $(".hcenter").outerWidth()) / 2
});
};
$(window).resize(hCenter());
hCenter();