jQuery를 사용하여 DIV를 화면 중앙에 정렬하기
jQuery를 사용하여 DIV를 화면 중앙(가운데)에 정렬하려면 다음 jQuery 스크립트를 사용할 수 있습니다.
jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop()) + "px"); this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft()) + "px"); return this; } // Source: stackoverflow
다음 코드로 상위 DIV의 중앙에 정렬됩니다.
$("element").center();
수직(세로)으로는 가운데 정렬할 필요가 없으면 this.css("top",... ); 라인을 삭제하면 됩니다.
다음과 같은 jQuery 스크립트도 가능합니다.
$.fn.center = function() { this.css({ 'position': 'fixed', 'left': '50%', 'top': '50%' }); this.css({ 'margin-left': -this.outerWidth() / 2 + 'px', 'margin-top': -this.outerHeight() / 2 + 'px' }); return this; }
jQuery 대신 간단히 다음과 같은 CSS 코드를 사용할 수도 있습니다.
.center { position: absolute; /* */ left: 50%; top: 50%; transform: translate(-50%, -50%); width: 48%; height: 59%; }
CSS를 사용하려는 경우 위의 코드보다 div 내의 div를 중앙에 정렬하기 글에 소개된 방법을 사용해보시기 바랍니다. 거의 대부분의 경우에서 잘 작동합니다.
일부 글에 제휴 링크가 포함될 수 있으며 파트너스 활동으로 일정액의 수수료를 받을 수 있습니다.