문제

나는 어떻게 설정에 대해 <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();

데모: 깡깡이 (추가 매개 변수 포함)

다른 팁

나는 a 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 위치 유틸리티

$('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에서 기본 계산을 수행 할 수 있습니다.

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

나는 @tonyl이 제공 한 위대한 대답을 확장하고 있습니다. 나는 값을 감싸기 위해 math.abs ()를 추가하고 있으며, 예를 들어 WordPress에서와 같이 jQuery가 "충돌 없음"모드에있을 수 있음을 고려합니다.

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

내가하는 다른 일은 $ (창) 객체를 캐싱하여 추가 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 "테스트"가있는 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 Centering 플러그인을 발견했습니다. 그것은이라고 고정 센터.

이것은 테스트되지 않았지만 이와 같은 것이 효과가 있어야합니다.

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

이 기능의 전이 구성 요소는 크롬에서 나에게 실제로 제대로 작동하지 않았습니다 (다른 곳에서는 테스트하지 않았습니다). 나는 창문을 무리에 크기를 조정하고 내 요소는 따라 잡으려고 천천히 스카우트를 할 것입니다.

따라서 다음 기능은 그 부분을 설명합니다. 또한 옵션 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 Doc 사용에 따르면 .outerWidth(true) 마진을 포함해야하지만 크롬에서 시도했을 때 예상대로 작동하지 않았습니다.

그만큼 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 -그것은 심하게 해킹에 대한 즉만 제공합 순수 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/

잘못입니다! 수평 위치를 확인이지만,수직으로...Oh,I see.분명히 css,을 설정할 때 상위 여백%,이 값은 다음과 같이 계산됩니다 백분율에 항상 상대 의 블록을 포함하는.사과와 오렌지!을 신뢰하지 않는 경우 나나 Mozilla doco,플레이로 바이올린은 위의 조정하여 컨텐트 너비와 깜짝 놀라게 할 것이다.


지금,CSS 나의 빵,버터,나만의 이야기가 아닙니다.동시에,내가 선호하는 일이 쉬운,그래서 빌려 연구 결과의 Czech CSS 전문가 고 작업으로 바이올린.Long story short,우리는 테이블을 작성하는 수직 정렬은 중간에 설정:

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

고 보다는 내용의 위치를 정밀 조정과 옛 margin:0auto;:

.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');
        }
    };

i use this:

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

Please use this:

$(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();

you're getting that poor transition because you're adjusting the position of the element every time the document is scrolled. What you want is to use fixed positioning. I tried that fixed center plugin listed above and that seems to do solve the problem nicely. Fixed positioning allows you to center an element once, and the CSS property will take care of maintaining that position for you every time you scroll.

Here is my version. I may change it after I look at these examples.

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

No need jquery for this

I used this to center Div element. Css Style,

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

Open element

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

});

MY UPDATE TO TONY L'S ANSWER This is the modded version of his answer that I use religiously now. I thought I would share it, as it adds slightly more functionality to it for various situations you may have, such as different types of position or only wanting horizontal/vertical centering rather than both.

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

In my <head>:

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

Examples of usage:

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

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

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

It works with any positioning type, and can be used throughout your entire site easily, as well as easily portable to any other site you create. No more annoying workarounds for centering something properly.

Hope this is useful for someone out there! Enjoy.

Lot's of ways to do this. My object is kept hidden with display:none just inside the BODY tag so that positioning is relative to the BODY. After using $("#object_id").show(), I call $("#object_id").center()

I use position:absolute because it is possible, especially on a small mobile device, that the modal window is larger than the device window, in which case some of the modal content could be inaccessible if positioning was fixed.

Here's my flavor based on other's answers and my specific needs:

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

Normally, I would do this with CSS only... but since you asked you a way to do this with jQuery...

The following code centers a div both horizontally and vertically inside its container :

$("#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>

(see also this Fiddle)

CSS solution In two lines only

It centralize your inner div horizontally and vertically.

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

}

for only horizontal align, change

margin: 0 auto;

and for vertical, change

margin: auto 0;

You could use the CSS translate property:

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

Read this post for more details.

Why you don't use CSS for centering a div?

#timer_wrap{  
  position: fixed;
  left: 50%;
  top: 50%;
} 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top