Skip to content

Instantly share code, notes, and snippets.

@vaibhavpandeyvpz
Last active November 8, 2019 03:09
Show Gist options
  • Save vaibhavpandeyvpz/61009eafac75d34c3f03776ba1ee0a80 to your computer and use it in GitHub Desktop.
Save vaibhavpandeyvpz/61009eafac75d34c3f03776ba1ee0a80 to your computer and use it in GitHub Desktop.
Center an element horizontally and/or vertically using JavaScript.
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