javascript - Absolute center with jquery return margin-left 0 -
javascript - Absolute center with jquery return margin-left 0 -
i have designed jquery plug-in website, purpose of helping center element absolute position, using pixels , not percentage. when page starts, elements centered vertically not horizontally (margin-left=0). when utilize same script in console, apply element , works.
code append function :
$(document).ready(function() { $(element).psfcenter(); });
function :
(function ($){ // center element $.fn.psfcenter=function(orientation){ homecoming 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 give element left 50% , margin-left half of width. because want have working on smaller device (responsive).
something this: http://jsfiddle.net/bsxqml6f/
class="snippet-code-js lang-js prettyprint-override">$.fn.psfcenter = function(orientation) { homecoming 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 deviding 2 }; var set_top = function() { self.css({ 'top': '50%', 'margin-top': '-' + (inner_height * .5) + 'px' }); // faster deviding 2 }; set_absolute(); switch(orientation) { case 'x': set_top(); break; case 'y': set_left(); break; default: set_left(); set_top(); break; } }); } $('.center-me').psfcenter();
class="snippet-code-css lang-css prettyprint-override">.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; }
class="snippet-code-html lang-html prettyprint-override"><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>
javascript jquery centering absolute
Comments
Post a Comment