Last active
November 8, 2019 03:09
-
-
Save vaibhavpandeyvpz/61009eafac75d34c3f03776ba1ee0a80 to your computer and use it in GitHub Desktop.
Center an element horizontally and/or vertically using JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function resize($el) { | |
const data = $el.data('center'); | |
if (data.x) { | |
const w_width = $(window).width(); | |
const e_width = $el.width(); | |
const margin = (w_width - e_width) / 2; | |
$el.css('left', margin) | |
} | |
if (data.y) { | |
const w_height = $(window).height(); | |
const e_height = $el.height(); | |
const margin = (w_height - e_height) / 2; | |
$el.css('top', margin) | |
} | |
} | |
$('[data-center]').each(function () { | |
const $this = $(this).css('position', 'absolute'); | |
$(document).ready(() => resize($this)); | |
$(window).on('resize', () => resize($this)) | |
}); | |
// Use it like <img ... data-center='{"x": true, "y": true}'> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment