your programing

jQuery를 사용하여 DIV를 화면 중앙에 배치

lovepro 2020. 9. 29. 08:18
반응형

jQuery를 사용하여 DIV를 화면 중앙에 배치


<div>jQuery를 사용하여 화면 중앙 에 설정하는 방법은 무엇입니까?


이 함수가 도움이되도록 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;
}

이제 다음과 같이 작성할 수 있습니다.

$(element).center();

데모 : Fiddle (매개 변수 추가)


여기에 jquery 플러그인을 넣었습니다.

매우 짧은 버전

$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});

짧은 버전

(function($){
    $.fn.extend({
        center: function () {
            return this.each(function() {
                var top = ($(window).height() - $(this).outerHeight()) / 2;
                var left = ($(window).width() - $(this).outerWidth()) / 2;
                $(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
            });
        }
    }); 
})(jQuery);

이 코드로 활성화 :

$('#mainDiv').center();

플러그인 버전

(function($){
     $.fn.extend({
          center: function (options) {
               var options =  $.extend({ // Default values
                    inside:window, // element, center into window
                    transition: 0, // millisecond, transition time
                    minX:0, // pixel, minimum left element value
                    minY:0, // pixel, minimum top element value
                    withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
                    vertical:true, // booleen, center vertical
                    horizontal:true // booleen, center horizontal
               }, options);
               return this.each(function() {
                    var props = {position:'absolute'};
                    if (options.vertical) {
                         var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
                         if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
                         top = (top > options.minY ? top : options.minY);
                         $.extend(props, {top: top+'px'});
                    }
                    if (options.horizontal) {
                          var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
                          if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
                          left = (left > options.minX ? left : options.minX);
                          $.extend(props, {left: left+'px'});
                    }
                    if (options.transition > 0) $(this).animate(props, options.transition);
                    else $(this).css(props);
                    return $(this);
               });
          }
     });
})(jQuery);

이 코드로 활성화 :

$(document).ready(function(){
    $('#mainDiv').center();
    $(window).bind('resize', function() {
        $('#mainDiv').center({transition:300});
    });
);

맞습니까?

업데이트 :

에서 CSS-트릭

.center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%); /* Yep! */
  width: 48%;
  height: 59%;
}

jQueryUI Position 유틸리티를 권장 합니다.

$('your-selector').position({
    of: $(window)
});

센터링보다 훨씬 더 많은 가능성을 제공합니다 ...


여기에 내 방법이 있습니다. 결국 Lightbox 클론에 사용했습니다. 이 솔루션의 가장 큰 장점은 창 크기를 조정하더라도 요소가 자동으로 중앙에 유지되어 이러한 종류의 사용에 이상적이라는 것입니다.

$.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;
}

다음과 같이 중앙에 CSS 만 사용할 수 있습니다.

작업 예

.center{
    position: absolute;
    height: 50px;
    width: 50px;
    background:red;
    top:calc(50% - 50px/2); /* height divided by 2*/
    left:calc(50% - 50px/2); /* width divided by 2*/
}
<div class="center"></div>

calc() CSS로 기본적인 계산을 할 수 있습니다.

calc()브라우저 지원 테이블에 대한 MDN 문서


@TonyL이 제공하는 훌륭한 답변을 확장하고 있습니다. 값을 래핑하기 위해 Math.abs ()를 추가하고 있으며, 예를 들어 WordPress에서와 같이 jQuery가 "충돌 없음"모드에있을 수 있음을 고려합니다.

아래에서 설명한 것처럼 Math.abs ()로 위쪽 및 왼쪽 값을 래핑하는 것이 좋습니다. 창이 너무 작고 모달 대화 상자 상단에 닫기 상자가 있으면 닫기 상자가 표시되지 않는 문제를 방지 할 수 있습니다. Tony의 기능은 잠재적으로 음수 값을 가졌을 것입니다. 음수 값으로 끝나는 방법에 대한 좋은 예는 중앙에 큰 대화 상자가 있지만 최종 사용자가 여러 도구 모음을 설치하거나 기본 글꼴을 늘린 경우입니다.이 경우 모달 대화 상자의 닫기 상자 ( 표시되지 않고 클릭 할 수 없습니다.

내가하는 다른 일은 $ (window) 객체를 캐싱하여 약간의 속도를 높여서 추가 DOM 순회를 줄이고 클러스터 CSS를 사용하는 것입니다.

jQuery.fn.center = function ($) {
  var w = $(window);
  this.css({
    'position':'absolute',
    'top':Math.abs(((w.height() - this.outerHeight()) / 2) + w.scrollTop()),
    'left':Math.abs(((w.width() - this.outerWidth()) / 2) + w.scrollLeft())
  });
  return this;
}

사용하려면 다음과 같이하십시오.

jQuery(document).ready(function($){
  $('#myelem').center();
});

jQuery UI position 기능을 사용합니다 .

작동 데모를 참조하십시오 .

<div id="test" style="position:absolute;background-color:blue;color:white">
    test div to center in window
</div>

ID가 "test"인 div가 가운데에있는 경우 다음 스크립트는 문서가 준비된 창에서 div를 가운데에 배치합니다. (위치 옵션에서 "my"및 "at"의 기본값은 "center")

<script type="text/javascript">
$(function(){
  $("#test").position({
     of: $(window)
  });
};
</script>

한 가지 문제를 수정하고 싶습니다.

this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");

위의 코드는 this.height(사용자가 화면 크기를 조정하고 콘텐츠가 동적이라고 가정) 다음 과 같은 경우에는 작동하지 않습니다 scrollTop() = 0.

window.height입니다 600
this.height입니다650

600 - 650 = -50  

-50 / 2 = -25

이제 상자가 -25화면 중앙에 있습니다.


요소를 항상 페이지 중앙에 배치하려는 경우 절대 위치를 갖는 것이 가장 좋을 것이라고 생각하지 않습니다. 고정 된 요소를 원할 것입니다. 고정 위치를 사용하는 다른 jquery 센터링 플러그인을 찾았습니다. 고정 센터 라고 합니다.


이것은 테스트되지 않았지만 이와 같은 것이 작동합니다.

var myElement = $('#myElement');
myElement.css({
    position: 'absolute',
    left: '50%',
    'margin-left': 0 - (myElement.width() / 2)
});

이 기능의 전환 구성 요소는 Chrome에서 저에게 정말 제대로 작동하지 않았습니다 (다른 곳에서는 테스트하지 않았습니다). 창 크기를 조정하면 요소가 천천히 돌아 다니며 따라 잡으려고합니다.

따라서 다음 함수는 그 부분을 설명합니다. 또한 가로로가 아닌 세로로 중앙에 배치하려는 경우 선택적 x & y 부울을 전달하기위한 매개 변수를 추가했습니다. 예를 들면 다음과 같습니다.

// Center an element on the screen
(function($){
  $.fn.extend({
    center: function (x,y) {
      // var options =  $.extend({transition:300, minX:0, minY:0}, options);
      return this.each(function() {
                if (x == undefined) {
                    x = true;
                }
                if (y == undefined) {
                    y = true;
                }
                var $this = $(this);
                var $window = $(window);
                $this.css({
                    position: "absolute",
                });
                if (x) {
                    var left = ($window.width() - $this.outerWidth())/2+$window.scrollLeft();
                    $this.css('left',left)
                }
                if (!y == false) {
            var top = ($window.height() - $this.outerHeight())/2+$window.scrollTop();   
                    $this.css('top',top);
                }
        // $(this).animate({
        //   top: (top > options.minY ? top : options.minY)+'px',
        //   left: (left > options.minX ? left : options.minX)+'px'
        // }, options.transition);
        return $(this);
      });
    }
  });
})(jQuery);

브라우저 뷰포트 (창)를 기준으로 요소를 중앙에 배치하려면을 사용하지 마세요 position: absolute. 올바른 위치 값은 다음과 같아야합니다 fixed(절대적 의미 : "요소가 첫 번째 위치 (정적 아님) 상위 요소를 기준으로 배치됨").

제안 된 센터 플러그인의이 대체 버전은 "px"대신 "%"를 사용하므로 창 크기를 조정할 때 콘텐츠가 중앙에 유지됩니다.

$.fn.center = function () {
    var heightRatio = ($(window).height() != 0) 
            ? this.outerHeight() / $(window).height() : 1;
    var widthRatio = ($(window).width() != 0) 
            ? this.outerWidth() / $(window).width() : 1;

    this.css({
        position: 'fixed',
        margin: 0,
        top: (50*(1-heightRatio)) + "%",
        left: (50*(1-widthRatio))  + "%"
    });

    return this;
}

margin: 0너비 / 높이에서 콘텐츠 여백을 제외 해야합니다 (고정 된 위치를 사용하기 때문에 여백을 갖는 것은 의미가 없습니다). jQuery 문서에 따르면 .outerWidth(true)여백을 포함해야하지만 Chrome에서 시도했을 때 예상대로 작동하지 않았습니다.

50*(1-ratio)에서 온다 :

창 너비 : W = 100%

요소 폭 (%) : w = 100 * elementWidthInPixels/windowWidthInPixels

중앙 왼쪽을 계산하는 방법 :

 left = W/2 - w/2 = 50 - 50 * elementWidthInPixels/windowWidthInPixels =
 = 50 * (1-elementWidthInPixels/windowWidthInPixels)

이것은 훌륭합니다. 콜백 함수를 추가했습니다.

center: function (options, callback) {


if (options.transition > 0) {
   $(this).animate(props, options.transition, callback);
} else { 
    $(this).css(props);
   if (typeof callback == 'function') { // make sure the callback is a function
       callback.call(this); // brings the scope to the callback
   }
}

편집하다:

질문이 나에게 가르쳐 준 것이 있다면, 그것은 이것입니다 : 이미 작동하는 것을 바꾸지 마십시오 :)

나는 이것이 http://www.jakpsatweb.cz/css/css-vertical-center-solution.html 에서 어떻게 처리되었는지에 대한 (거의) 축 어적 사본을 제공하고 있습니다-IE를 위해 심하게 해킹되었지만 순수한 CSS 방법을 제공합니다. 질문에 대답 :

.container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}
.helper    {#position:absolute; #top:50%;
            display:table-cell; vertical-align:middle;}
.content   {#position:relative; #top:-50%;
            margin:0 auto; width:200px; border:1px solid orange;}

바이올린 : http://jsfiddle.net/S9upd/4/

나는 이것을 browsershots를 통해 실행했고 괜찮아 보인다. 다른 것이 없다면 CSS 사양에 따라 처리되는 여백 비율이 빛을 볼 수 있도록 원본을 아래에 보관하겠습니다.

실물:

파티에 늦었 나봐!

위의 의견은 이것이 CSS 질문이라는 것을 암시합니다. 나 CSS는 것을 말하여이 서문 보자 정말 이 일에 발에서 자신을 촬영. 이 작업을 수행하는 것이 얼마나 쉬울까요?

.container {
    position:absolute;
    left: 50%;
    top: 50%;
    overflow:visible;
}
.content {
    position:relative;
    margin:-50% 50% 50% -50%;
}

권리? 컨테이너의 왼쪽 상단 모서리는 화면 중앙에 있고 음수 여백이 있으면 콘텐츠가 페이지의 절대 중앙에 마술처럼 다시 나타납니다! http://jsfiddle.net/rJPPc/

잘못된! 수평 위치는 괜찮지 만 수직으로는 ... 아, 알겠습니다. 분명히 CSS에서 위쪽 여백을 %로 설정할 때 값은 항상 포함 블록 너비상대적인 백분율 로 계산됩니다. 사과와 오렌지처럼! 저나 Mozilla doco를 믿지 않는다면 콘텐츠 너비를 조정하여 위의 바이올린을 연주하고 놀랍니다.


이제 CSS가 제 빵이자 버터이기 때문에 포기하지 않았습니다. 동시에 저는 쉬운 것을 선호하기 때문에 체코 CSS 전문가 의 결과를 빌려 작업하는 바이올린으로 만들었습니다. 간단히 말해 세로 정렬이 가운데로 설정된 테이블을 만듭니다.

<table class="super-centered"><tr><td>
    <div class="content">
        <p>I am centered like a boss!</p>
    </div>
</td></tr></table>

그리고 콘텐츠의 위치는 좋은 오래된 여백으로 미세 조정됩니다 . :

.super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}
.content {margin:0 auto;width:200px;}​

약속대로 작동하는 바이올린 : http://jsfiddle.net/teDQ2/


내가 여기있는 것은 중앙에 배치하려는 요소가 "고정"또는 "절대"위치 일뿐만 아니라 중앙에 배치하는 요소가 상위 요소보다 작은 지 확인하는 "중앙"방법입니다. 요소와 관련된 요소는 부모입니다. 요소 부모가 요소 자체보다 작 으면 DOM을 다음 부모로 약화시키고 그에 상대적인 중앙에 배치합니다.

$.fn.center = function () {
        /// <summary>Centers a Fixed or Absolute positioned element relative to its parent</summary>

        var element = $(this),
            elementPos = element.css('position'),
            elementParent = $(element.parent()),
            elementWidth = element.outerWidth(),
            parentWidth = elementParent.width();

        if (parentWidth <= elementWidth) {
            elementParent = $(elementParent.parent());
            parentWidth = elementParent.width();
        }

        if (elementPos === "absolute" || elementPos === "fixed") {
            element.css('right', (parentWidth / 2) - elementWidth / 2 + 'px');
        }
    };

나는 이것을 사용한다 :

$(function() {
   $('#divId').css({
    'left' : '50%',
    'top' : '50%',
    'position' : 'absolute',
    'margin-left' : -$('#divId').outerWidth()/2,
    'margin-top' : -$('#divId').outerHeight()/2
  });
});

이것을 사용하십시오 :

$(window).resize(function(){
    $('.className').css({
        position:'absolute',
        left: ($(window).width() - $('.className').outerWidth())/2,
        top: ($(window).height() - $('.className').outerHeight())/2
    });
});

// To initially run the function:
$(window).resize();

문서가 스크롤 될 때마다 요소의 위치를 ​​조정하기 때문에 전환이 좋지 않습니다. 원하는 것은 고정 위치를 사용하는 것입니다. 위에 나열된 고정 센터 플러그인을 시도했는데 문제를 잘 해결하는 것 같습니다. 고정 위치를 사용하면 요소를 한 번 중앙에 배치 할 수 있으며 스크롤 할 때마다 CSS 속성이 해당 위치를 유지합니다.


여기 내 버전입니다. 이 예제를 본 후에 변경할 수 있습니다.

$.fn.pixels = function(property){
    return parseInt(this.css(property));
};

$.fn.center = function(){
    var w = $($w);
    return this.each(function(){
        $(this).css("position","absolute");
        $(this).css("top",((w.height() - $(this).height()) / 2) - (($(this).pixels('padding-top') + $(this).pixels('padding-bottom')) / 2) + w.scrollTop() + "px");
        $(this).css("left",((w.width() - $(this).width()) / 2) - (($(this).pixels('padding-left') + $(this).pixels('padding-right')) / 2) + w.scrollLeft() + "px");
    });
};

이것에 대한 jquery가 필요하지 않습니다.

나는 이것을 Div 요소를 중앙에 사용했습니다. CSS 스타일,

.black_overlay{
    display: none;
    position: absolute;
    top: 0%;
    left: 0%;
    width: 100%;
    height: 100%;
    background-color: black;
    z-index:1001;
    -moz-opacity: 0.8;
    opacity:.80;
    filter: alpha(opacity=80);
}

.white_content {
    display: none;
    position: absolute;
    top: 25%;
    left: 25%;
    width: 50%;
    height: 50%;
    padding: 16px;
    border: 16px solid orange;
    background-color: white;
    z-index:1002;
    overflow: auto;
}

요소 열기

$(document).ready(function(){
    $(".open").click(function(e){
      $(".black_overlay").fadeIn(200);
    });

});

토니 엘의 대답에 대한 나의 업데이트 이것은 내가 지금 종교적으로 사용하는 그의 대답의 수정 된 버전입니다. 나는 그것을 공유 할 것이라고 생각했다. 그것은 당신이 가질 수있는 다양한 상황에 대해 약간 더 많은 기능을 추가하기 때문 position이다.

center.js :

// We add a pos parameter so we can specify which position type we want

// Center it both horizontally and vertically (dead center)
jQuery.fn.center = function (pos) {
    this.css("position", pos);
    this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
    this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
    return this;
}

// Center it horizontally only
jQuery.fn.centerHor = function (pos) {
    this.css("position", pos);
    this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
    return this;
}

// Center it vertically only
jQuery.fn.centerVer = function (pos) {
    this.css("position", pos);
    this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
    return this;
}

<head>:

<script src="scripts/center.js"></script>

사용 예 :

$("#example1").centerHor("absolute")
$("#example2").centerHor("fixed")

$("#example3").centerVer("absolute")
$("#example4").centerVer("fixed")

$("#example5").center("absolute")
$("#example6").center("fixed")

모든 포지셔닝 유형에서 작동하며 전체 사이트에서 쉽게 사용할 수있을뿐만 아니라 사용자가 만든 다른 사이트로 쉽게 이동할 수 있습니다. 무언가를 적절하게 중앙에 배치하기위한 더 이상 성가신 해결 방법이 없습니다.

이것이 누군가에게 유용하기를 바랍니다! 즐겨.


이를 수행하는 방법은 다양합니다. 내 개체는 BODY 태그 바로 안에 display : none으로 숨겨져 있으므로 위치는 BODY를 기준으로합니다. $ ( "# object_id"). show ()를 사용한 후 $ ( "# object_id"). center ()를 호출 합니다.

특히 작은 모바일 장치에서 모달 창이 장치 창보다 클 수 있기 때문에 position : absolute를 사용 합니다.이 경우 위치가 고정 된 경우 일부 모달 콘텐츠에 액세스 할 수 없습니다.

다른 사람의 답변과 특정 요구 사항에 따른 내 취향은 다음과 같습니다.

$.fn.center = function () {
        this.css("position","absolute");

        //use % so that modal window will adjust with browser resizing
        this.css("top","50%");
        this.css("left","50%");

        //use negative margin to center
        this.css("margin-left",(-1*this.outerWidth()/2)+($(window).scrollLeft())+"px");
        this.css("margin-top",(-1*this.outerHeight()/2)+($(window).scrollTop())+"px");

        //catch cases where object would be offscreen
        if(this.offset().top<0)this.css({"top":"5px","margin-top":"0"});
        if(this.offset().left<0)this.css({"left":"5px","margin-left":"0"});

        return this;
    };

일반적으로 CSS로만이 작업을 수행하지만 jQuery로이 작업을 수행하는 방법을 요청했기 때문에 ...

다음 코드는 컨테이너 내부에서 div를 가로 및 세로 중앙에 배치합니다.

$("#target").addClass("centered-content")
            .wrap("<div class='center-outer-container'></div>")
            .wrap("<div class='center-inner-container'></div>");
body {
    margin : 0;
    background: #ccc;
}

.center-outer-container {
    position : absolute;
    display: table;
    width: 100%;
    height: 100%;
}

.center-inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<div id="target">Center this!</div>

( 이 Fiddle 참조 )


CSS 솔루션 두 줄로만

내부 div를 수평 및 수직으로 중앙 집중화합니다.

#outer{
  display: flex;
}
#inner{
margin: auto;

}

수평 정렬, 변경

margin: 0 auto;

수직의 경우 변경

margin: auto 0;

CSS translate속성을 사용할 수 있습니다 .

position: absolute;
transform: translate(-50%, -50%);

자세한 내용은 이 게시물읽으십시오 .


div 중심화에 CSS를 사용하지 않는 이유는 무엇입니까?

#timer_wrap{  
  position: fixed;
  left: 50%;
  top: 50%;
} 

참고 URL : https://stackoverflow.com/questions/210717/using-jquery-to-center-a-div-on-the-screen

반응형