I have designed a JQuery plug-in for a website, with the purpose of helping center an element with absolute position, using pixels and not percentage. When the page starts, elements are centered vertically but not horizontally (margin-left=0). When I use the same script in console, I apply to an element and it works.
Code to append the function :
$(document).ready(function() {
$(element).psfCenter();
});
Function :
(function ($){
// center element
$.fn.psfCenter=function(orientation){
return this.each(function() {
var widthParent=$(this).parent().width()/2;
var heightParent=$(this).parent().height()/2;
var widthElement=$(this).width()/2;
var heightElement=$(this).height()/2;
var left=widthParent-widthElement;
var top=heightParent-heightElement;
console.log(orientation)
switch(orientation){
case"x":
$(this).css({
'position':'absolute',
'margin-left':left,
})
break;
case "y":
$(this).css({
'position':'absolute',
'margin-top':top
})
break;
default:
$(this).css({
'position':'absolute',
'margin-left':left,
'margin-top':top
})
break;
}
});
};
})(jQuery);
I would give the element left 50% and than margin-left the half of its width. This because you probably want to have it working on a smaller device (responsive).
Something like this: http://jsfiddle.net/bsxqmL6f/
$.fn.psfCenter = function(orientation) { return this.each(function() { var self = $(this); var inner_width = self.width(); var inner_height = self.height(); var set_absolute = function() { self.css('position', 'absolute'); } var set_left = function() { self.css({ 'left': '50%', 'margin-left': '-' + (inner_width * .5) + 'px' }); // faster than deviding by 2 }; var set_top = function() { self.css({ 'top': '50%', 'margin-top': '-' + (inner_height * .5) + 'px' }); // faster than deviding by 2 }; set_absolute(); switch(orientation) { case 'x': set_top(); break; case 'y': set_left(); break; default: set_left(); set_top(); break; } }); } $('.center-me').psfCenter();
.center-me { width: 50px; height: 50px; background-color: red; } .huge { width: 250px; height: 250px; background-color: yellow; } .smaller { width: 120px; height: 120px; background-color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="center-me huge"></div> <div class="center-me smaller"></div> <div class="center-me"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.