수직 중심 부트 스트랩 모달 창


181

뷰포트 (가운데)에 모달을 중앙에 놓고 싶습니다 .CSS 속성을 추가하려고했습니다.

 .modal { position: fixed; top:50%; left:50%; }   

이 예제를 사용하고 있습니다 http://jsfiddle.net/rniemeyer/Wjjnd/

나는 시도했다

$("#MyModal").modal('show').css(
    {
        'margin-top': function () {
            return -($(this).height() / 2);
        },
        'margin-left': function () {
            return -($(this).width() / 2);
        }
    })

오버라이드 .modal.fade.in도 시도해보십시오
— haim770


3
이 zerosixthree.se/…를 사용해보십시오. 나는 다음을 사용합니다. .modal.fade.in {top : 50 %; 변환 : translateY (-50 %); }
— jowan sebastian

flexbox 솔루션 추가 ( translateY(-50%)모달 내용이 장치 높이보다 높을 경우 모달 상단에 액세스 할 수 없음)
— tao

부트 스트랩 4에서 모달 대화 상자 중심으로 추가되어 더 이상 필요하지 않습니다. 아래에서 해당 답변을 검토하십시오.
— jcaruso

답변:


258

이것은 작업을 수행합니다 : http://jsfiddle.net/sRmLV/1140/

helper-div와 일부 사용자 정의 CSS를 사용합니다. 자바 스크립트 나 jQuery가 필요하지 않습니다.

HTML (부트 스트랩의 데모 코드 기반 )

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="vertical-alignment-helper">
        <div class="modal-dialog vertical-align-center">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>

                    </button>
                     <h4 class="modal-title" id="myModalLabel">Modal title</h4>

                </div>
                <div class="modal-body">...</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

.vertical-alignment-helper {
    display:table;
    height: 100%;
    width: 100%;
    pointer-events:none; /* This makes sure that we can still click outside of the modal to close it */
}
.vertical-align-center {
    /* To center vertically */
    display: table-cell;
    vertical-align: middle;
    pointer-events:none;
}
.modal-content {
    /* Bootstrap sets the size of the modal in the modal-dialog class, we need to inherit it */
    width:inherit;
    max-width:inherit; /* For Bootstrap 4 - to avoid the modal window stretching full width */
    height:inherit;
    /* To center horizontally */
    margin: 0 auto;
    pointer-events: all;
}

이 솔루션으로 높이 때문에 : 100 %; 폭 : 100 %; 모달을 클릭하여 모달을 닫을 수 없습니다. 이 @Rens de Nobel에 대한 해결책을 생각할 수 있습니까?
— pcatre

1
좋아,이 솔루션은 훌륭하게 작동하는 것으로 보입니다 (모달을 클릭하여 모달을 닫지 못하게하는 것을 제외하고). 그러나 어떻게 든 그것은 각도기에서 내 e2e 테스트 중 일부를 실패하게 만듭니다 (그리고 나는 이것이 버그라고 생각하지 않는 이유를 찾을 수 없습니다). 어쨌든 나는 자바 스크립트 답변으로 돌아가서 더 많은 시간을 잃지 않습니다. 그러나 내가 말했듯이, 이것은 잘 작동하는 것처럼 보이며, 각도기에서 e2e 테스트를 수행하는 사람들에게 경고합니다.
— pcatre

3
@ pcatre, 팁 주셔서 감사합니다! 이 문제를 해결하기 위해 코드를 업데이트했습니다. 포인터 이벤트 설정 : 없음; 정렬 클래스에서 트릭을 수행합니다. IE11, 최신 Chrome 및 Firefox 및 iOS Safari에서 테스트되었습니다.
— RNobel

4
내부의 모달 요소를 클릭하면 작동하지 않는다고 말하는 사용자의 의견 때문에 이것이 업데이트되었는지 확실하지 않지만 위의 바이올린의 예제를 사용하여 현재 100 % 작동합니다. 귀하의 도움과 위의 모든 의견에 감사드립니다.
— Michael G

2
부트 스트랩 4에서 모달 대화 상자 중심으로 추가되어 더 이상 필요하지 않습니다. 아래에서 해당 답변을 검토하십시오.
— jcaruso

94

gpcola의 답변이 저에게 효과적이지 않기 때문에 조금 편집하여 작동합니다. 변환 대신 "마진 상단"을 사용했습니다. 또한 "shown"이벤트 대신 "show"를 사용합니다. 왜냐하면 포지셔닝의 점프가 매우 나빴 기 때문입니다 (부트 스트랩 애니메이션이 켜져있을 때 표시됨). 위치를 지정하기 전에 디스플레이를 "block"으로 설정하십시오. 그렇지 않으면 $ dialog.height ()가 0이되고 모달이 완전히 중앙에 위치하지 않습니다.

(function ($) {
    "use strict";
    function centerModal() {
        $(this).css('display', 'block');
        var $dialog  = $(this).find(".modal-dialog"),
        offset       = ($(window).height() - $dialog.height()) / 2,
        bottomMargin = parseInt($dialog.css('marginBottom'), 10);

        // Make sure you don't hide the top part of the modal w/ a negative margin if it's longer than the screen height, and keep the margin equal to the bottom margin of the modal
        if(offset < bottomMargin) offset = bottomMargin;
        $dialog.css("margin-top", offset);
    }

    $(document).on('show.bs.modal', '.modal', centerModal);
    $(window).on("resize", function () {
        $('.modal:visible').each(centerModal);
    });
}(jQuery));

6
이것은 완벽하다! $ (document) .height () 대신 4 행에서 $ (window) .height ()를 사용하는 것이 정확합니다. 또한 마지막 행을 다음과 같이 변경합니다. $('.modal:visible').each(centerModal);
— Denis Chmel

그것은 나를 위해 완벽하게 작동합니다, 감사합니다. 이 코드를 사용할 때 모달 대화 상자의 상단 및 하단 패딩을 0px로 설정하여 완벽한 중심에 맞 춥니 다.
— mina morsali 12

모달이 창의 높이보다 높으면 중단됩니다. 대화 상자의 여백을 설정하기 전에 다음 줄을 추가했습니다 if(offset < 0) offset = 0; . 전체 블록을 명확하지 않은 답변 사례에 붙여 넣습니다!
— jetlej 2016 년

나는 대답 아래에서, 모달의 아래쪽 여백에 동일 상단 마진을 유지하기 위해 몇 가지 추가 변경을 추가
— jetlej

완벽, 누락 $ (this) .css ( 'display', 'block'); 항상 높이가 왜 0인지 생각했습니다.
— Jānis Gruzis

81

이것이 내 앱에서 한 일입니다. bootstrap.css 파일에서 다음 클래스를 살펴보면 .modal-dialog의 기본 패딩은 10px 및 @media 화면이고 (최소 너비 : 768px) .modal-dialog의 상단 패딩은 30px로 설정되어 있습니다. 따라서 사용자 정의 CSS 파일에서 미디어 화면 너비를 지정하지 않고 모든 화면에서 상단 패딩을 15 %로 설정했습니다. 도움이 되었기를 바랍니다.

.modal-dialog {
  padding-top: 15%;
}

6
이것은 작은 alret 상자에서만 작동하며 larg 상자에서는 작동하지 않습니다.
— mina morsali 12

작은 모달에도 적용 할 수 있습니다 :.modal-dialog.modal-sm { padding-top:15%; }
— Dunc

61

모든 HTML5 브라우저에서 찾은 가장 좋은 방법 :

body.modal-open .modal {
    display: flex !important;
    height: 100%;
} 

body.modal-open .modal .modal-dialog {
    margin: auto;
}

2
나는이 솔루션을 매우 깨끗하게 좋아했습니다. 확실하지 바탕 화면 또는 그 이상 사파리 버전하지만 대한이 아이폰 OS 8. 벌금을 것 같다
— 니콜라스 Galler

1
네, @NicolasGaller에 동의합니다. 그것은 나에게도 잘 작동합니다. Chrome과 Firefox에서 테스트했습니다. 잘 작동한다.
— Manjunath Reddy

2
이것은 훌륭한 CSS 전용 점진적 향상입니다. js가 필요하지 않으며 flexbox를 지원하지 않는 브라우저는 기본 부트 스트랩 모달 배치를 갖습니다.
— Craig Harshbarger

닫기, 그러나 페이지에 둘 이상이있을 때 모달을 닫을 수 없습니다. 수정하려면 아래 답변을 참조하십시오.
— Robert McKee

1
업데이트 : 추가 align-items: center;가 body.modal-open .modal작동 하는 것 같습니다.
— bernie

20
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="table">
        <div class="table-cell">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
                    </div>
                    <div class="modal-body">
                        ...
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary">Save changes</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

// 스타일

.table {
 display: table;
 height:100%;
}
.table-cell {
display: table-cell;
vertical-align: middle;
}

3
이것이 보편적 인 답변입니다. 왜 아무도 투표하지 않았는지 모르겠습니다.
— Csaba Toth

3
나는 적어도 12 개의 제안서와 함께 적어도 4 개의 SO 엔트리를 겪었다. BTW, HTML5의 시대에 이것은 적어도 일부 프레임 워크에 기능적으로 내장되어야합니다. 저글링 대신.
— Csaba Toth

1
또한 참고 : 테이블 스타일에 너비 : 100 %를 말하면 모달이 오버플로 숨겨져 있지 않은 경우 수평 중심이 표시됩니다.
— Csaba Toth

1
최고의 답변. 이것은 스크롤바를 생성하지만 .modal-open .modal {overflow-y : hidden; }
— Christophe

14

.modal.fade.in에서 top 매개 변수를 재정 의하여 사용자 정의 선언에 설정된 값을 강제로 지정하고 !importanttop 뒤에 키워드를 추가하십시오 . 그러면 브라우저는 해당 값을 사용하고 키워드의 다른 값은 무시합니다. 여기에는 다른 곳에서는 값을 무시할 수 없다는 단점이 있습니다.

.modal {
    position: fixed;
    top: 50% !important;
    left: 50%;
}

이렇게하면 모달에 대한 배경을 클릭 할 때 모달을 닫을 수 없습니다.
— Scott Simpson

13

Bootstrap 4부터는 JavaScript없이이를 위해 다음 클래스가 추가되었습니다.

modal-dialog-centered

여기에서 해당 설명서를 찾을 수 있습니다 .

vd를 지적 해 주셔서 감사합니다. 모달을 세로로 가운데에 맞추려면 .modal-dialog-centered를 .modal-dialog에 추가해야합니다.


1
이것은 부트 스트랩 4에 가장 적합한 답변입니다.
— broc.seib 2016 년

모달 대화 상자와 모달 대화 상자 중심을 모두 추가하면 더 나은 결과를 얻을 수 있습니다
— vd

1
@vd는 문서에 ".modal-dialog-centered를 .modal-dialog에 추가하여 모달을 수직으로 가운데에 맞추십시오." 나는 그것을 잡지 않은 사람들에게도 그것을 반영하기 위해 대답을 업데이트 할 것입니다.
— jcaruso

12

이것은 나를 위해 완벽하게 작동합니다.

.modal {
text-align: center;
padding: 0!important;
}

.modal:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -4px;
}

.modal-dialog {
display: inline-block;
text-align: left;
vertical-align: middle;
}

완전한 데모 URL : https://codepen.io/dimbslmh/full/mKfCc


11

당신이 사용할 수있는:

.modal {
    position: fixed;
    top: 50% !important;
    left: 50%;
    transform: translate(-50%, -50%);
}

수직 및 수평으로 중앙에 배치합니다.


2
이것은 Flex를 사용하지 않고 CSS를 사용하여 진정한 "무엇을 중심에 두는가"입니다. 컨텍스트가 부트 스트랩이거나 모달이라는 사실은 관련이 없습니다. 다른 모든 답변은 너무 과도합니다.
— ESR

1
이 방법을 사용하면 모달이 장치 화면 높이보다 높으면 모달 상단에 액세스 할 수 없게됩니다.
— tao

11

여기에있는 대부분의 대답이 효과가 없거나 부분적으로 만 효과가 있었기 때문에 :

body.modal-open .modal[style]:not([style='display: none;']) {
    display: flex !important;
    height: 100%;
} 

body.modal-open .modal[style]:not([style='display: none;']) .modal-dialog {
    margin: auto;
}

모든 스타일 대신 현재 활성화 된 모달에만 스타일을 적용하려면 [style] 선택기를 사용해야합니다. .in훌륭했지만 전환이 완료된 후에 만 ​​추가되어 너무 늦어서 전환이 너무 나빠질 수 있습니다. 다행히 부트 스트랩은 모달에 스타일 속성을 항상 표시하는 것처럼 보이기 때문에 약간 해킹이지만 작동합니다.

이 :not([style='display: none;'])부분은 부트 스트랩이 스타일 속성을 올바르게 제거하지 않고 대신 대화 상자를 닫을 때 스타일 표시를 없음으로 설정하는 해결 방법입니다.


감사합니다 실제로 2016
— 효과가 있었던

4 년이 지났습니다. 여전히 유용합니다. 고마워 친구!
— Hassan Nomani

8

Bootstrap 3 모달에서 다음과 같이 수직 정렬 센터를 얻을 수 있습니다.

.modal-vertical-centered {
  transform: translate(0, 50%) !important;
  -ms-transform: translate(0, 50%) !important; /* IE 9 */
  -webkit-transform: translate(0, 50%) !important; /* Safari and Chrome */
}

이 CSS 클래스를 "모달 대화 상자"컨테이너에 추가하십시오.

<div class="modal-dialog modal-vertical-centered">
...

jsFiddle 작업 예 : http://jsfiddle.net/U4NRx/


대화 상자를 세로로 정확히 가운데에 배치하는 방법은 무엇입니까?
— gkalpak

대부분의 장소에서 잘 작동하지만 Android 4.4보다 낮은 래핑 된 html5 응용 프로그램에서는 작동하지 않습니다.
— Josh

3
내 모달 이이 페이지로 내려갔습니다
— Dorian

1
예! 나는 다음을 사용한다 : .modal.fade.in {top : 50 %; 변환 : translateY (-50 %); }
— jowan sebastian

50 %에서 15 %로 수정하면 대화 상자가 창 중앙에 나타납니다. .modal-vertical-centered {변환 : translate (0, 15 %)! 중요; -ms- 변환 : translate (0, 15 %)! 중요; / * IE 9 / -webkit-transform : translate (0, 15 %)! 중요; / Safari and Chrome * /}
— Haimei

8

가장 깨끗하고 간단한 방법은 Flexbox를 사용하는 것입니다! 다음은 화면 중앙에 Bootstrap 3 모달을 세로로 정렬하며 여기에 게시 된 다른 모든 솔루션보다 훨씬 깨끗하고 간단합니다.

body.modal-open .modal.in {
  display: flex !important;
  align-items: center;
}

참고 :이 방법이 가장 간단한 솔루션이지만 브라우저 지원으로 인해 일부 사용자에게는 작동하지 않을 수 있습니다. http://caniuse.com/#feat=flexbox

(일반적으로) IE가 뒤쳐지는 것처럼 보입니다. 필자의 경우, 본인 또는 고객을 위해 개발 한 모든 제품은 IE10 +입니다. 실제로 제품을 개발하고 MVP를 더 빨리 개발하는 데 사용할 수있을 때 이전 버전의 IE를 지원하는 개발 시간을 투자하는 것이 현명하지 않습니다. 이것은 모두가 가진 사치가 아닙니다.

더 큰 사이트는 flexbox가 지원되는지 여부를 감지하고 페이지 본문에 클래스를 적용하는 것을 보았습니다. 그러나 그 수준의 프론트 엔드 엔지니어링은 상당히 강력하며 여전히 폴 백이 필요합니다.

사람들이 웹의 미래를 받아들이도록 장려합니다. Flexbox는 훌륭하고 가능하면 사용을 시작해야합니다.

PS-이 사이트는 flexbox를 전체적으로 파악하여 모든 유스 케이스에 적용하는 데 실제로 도움이되었습니다. http://flexboxfroggy.com/

편집 : 한 페이지에 두 개의 모달의 경우 .modal.in에 적용됩니다.


그렇지 않으면 잘 작동하지만 닫기 애니메이션은 좋지 않습니다.
— user2061057

CSS3 전환으로 애니메이션을 구현할 수 있어야합니까?
— Greg Blass

7

장점 :

  • 장치보다 키가 큰 경우에도 액세스 할 수있는 모달 컨텐츠
  • 사용하지 않음 display:table-cell(레이아웃 용이 아님)
  • 기본 Bootstrap 3 모달을 수정할 필요가 없습니다. markup
  • 포지셔닝은 순수한 CSS입니다. 아래의 위 / 위의 클릭 / 탭에서 모달을 닫기 위해 JS가 추가되었습니다.
  • 또는 SCSS사용하는 사람들을 위해 접두사 를 포함하지 않았습니다.gulpgrunt

참고 : Bootstrap 3의 최신 사양 으로이 답변을 최신 상태로 유지하려고합니다. Bootstrap 4 솔루션의 경우이 답변을 참조하십시오 (현재는 다소 동일하지만 시간이 지남에 따라 다를 수 있음). 버그 나 문제가 발견되면 알려 주시면 업데이트하겠습니다. 감사.


접두사가없는 깨끗 SCSS( gulp/ 와 함께 사용 grunt) :

.modal-dialog {
  display: flex;
  flex-direction: column;
  justify-content: center;
  overflow-y: auto;
  min-height: calc(100vh - 60px);
  @media (max-width: 767px) {
    min-height: calc(100vh - 20px);
  }
}

2
최고의 솔루션 IMO.
— Radmation 2018 년

3

또 다른 CSS 솔루션. 보기 포트보다 큰 팝업에는 작동하지 않습니다.

.modal-dialog {
    position: absolute;
    right: 0;
    left: 0;
    margin-top: 0;
    margin-bottom: 0; 
}
.modal.fade .modal-dialog {
    transition: top 0.4s ease-out;
    transform: translate(0, -50%);
    top: 0;
}
.modal.in .modal-dialog {
    transform: translate(0, -50%);
    top: 50%;
}

에서는 .modal-dialog클래스 (상대적으로)에 절대 위치를 무시하고 콘텐츠 센터링right:0, left: 0

에 .modal.fade .modal-dialog , .modal.in .modal-dialog걸쳐 전환 애니메이션을 설정 top하지 않고 번역에 대한보다.

margin-top작은 팝업의 경우 팝업을 가운데 아래로 약간 이동시키고 긴 팝업의 경우 모달에 헤더가 붙어 있습니다. 그 후margin-top:0, margin-bottom:0

더 세분화해야합니다.


3

angular-ui 부트 스트랩을 사용하는 사람들은 위의 정보를 기반으로 아래 클래스를 추가 할 수 있습니다.

참고 : 다른 변경은 필요하지 않으며 모든 모달을 해결해야합니다.

// The 3 below classes have been placed to make the modal vertically centered
.modal-open .modal{
    display:table !important;
    height: 100%;
    width: 100%;
    pointer-events:none; /* This makes sure that we can still click outside of the modal to close it */
}

.modal-dialog{
    display: table-cell;
    vertical-align: middle;
    pointer-events: none;
}

.modal-content {
    /* Bootstrap sets the size of the modal in the modal-dialog class, we need to inherit it */
    width:inherit;
    height:inherit;
    /* To center horizontally */
    margin: 0 auto;
    pointer-events: all;
}

3

우리에게 자바 스크립트가 필요하지 않습니다. Boostrap 모달이 나타나면 클래스에 .in을 추가합니다. flex css를 사용하여 modalclassName.fade.in으로이 클래스 조합을 수정하면됩니다.

이 CSS를 추가하여 모달을 세로 및 가로로 가운데에 맞 춥니 다.

.modal.fade.in {
    display: flex !important;
    justify-content: center;
    align-items: center;
}
.modal.fade.in .modal-dialog {
    width: 100%;
}

2

내 선택, 약간의 CSS : (IE8에서는 작동하지 않음)

.modal.fade .modal-dialog {
    transform: translate(-50%, -80%);
}

.modal.in .modal-dialog {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    margin-top: 0px;
}

첫 번째 규칙을 사용하여 모달 표시 방법을 변경할 수 있습니다.

사용 : 부트 스트랩 3.3.4


2

다음 CSS를 기존 CSS에 추가하면 나에게 잘 작동합니다.

.modal {
  text-align: center;
}
@media screen and (min-width: 768px) {
    .modal:before {
      display: inline-block;
      vertical-align: middle;
      content: " ";
      height: 100%;
    }
}
.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}

2

Arany의 답변을 기반으로 하지만 페이지 스크롤을 고려합니다.

(function($) {
    "use strict";
    function positionModals(e) {
        var $this = $(this).css('display', 'block'),
            $window = $(window),
            $dialog = $this.find('.modal-dialog'),
            offset = ($window.height() - $window.scrollTop() - $dialog.height()) / 2,
            marginBottom = parseInt($dialog.css('margin-bottom'), 10);

        $dialog.css('margin-top', offset < marginBottom ? marginBottom : offset);
    }

    $(document).on('show.bs.modal', '.modal', positionModals);

    $(window).on('resize', function(e) {
        $('.modal:visible').each(positionModals);
    });
}(jQuery));

2

나는 이것이 Rens de Nobel의 솔루션보다 약간 깨끗한 순수한 CSS 솔루션이라고 생각합니다. 또한 대화 상자 외부를 클릭하여 대화 상자를 닫을 수 있습니다.

http://plnkr.co/edit/JCGVZQ?p=preview

.modal-dialog 클래스를 사용하여 CSS 클래스를 DIV 컨테이너에 추가하면 부트 스트랩 CSS보다 더 높은 특이성을 얻을 수 있습니다 (예 : .centered).

HTML

<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
  <div class="modal-dialog centered modal-lg">
    <div class="modal-content">
      ...
    </div>
  </div>
</div>

이 .modal-dialog.centered 컨테이너를 고정하고 올바르게 배치하십시오.

CSS

.modal .modal-dialog.centered {
    position: fixed;
    bottom: 50%;
    right: 50%;
    transform: translate(50%, 50%);
}

또는 flexbox를 사용하여 더 간단합니다.

CSS

.modal {
    display: flex;
    align-items: center;
    justify-content: center;
}

이 flexbox 버전은 예상대로 작동하지 않습니다. 최신 Chrome (52.0.x)에서 테스트 한 .modal-dialog는 제대로 중앙에 배치되었지만 이전에는 콘텐츠 상호 작용이 이상하게 보입니다. 그러나이 기술을 .modal-dialog (.modal이 아닌)에서 바로 사용할 수 있으며 다른 속성으로는 작동하는 것처럼 보입니다. =)
— giovannipds


1

이것은 v2에서 테스트되지 않은 BS3에서 작동합니다. 모달을 세로로 가운데에 맞 춥니 다. 이 위치로 전환됩니다. 위치에 CSS transition속성을 표시하려는 경우.modal-dialog

centerModal = function() {
    var $dialog = $(this).find(".modal-dialog"),
        offset = ($(window).height() - $dialog.height()) / 2;

    // Center modal vertically in window
    $dialog.css({
        'transform': 'translateY(' + offset + 'px) !important',
    });
};

$('.modal').on('shown.bs.modal', centerModal);
$(window).on("resize", function() {
    $('.modal').each(centerModal);
});

1
e(document).on('show.bs.modal', function () {
        if($winWidth < $(window).width()){
            $('body.modal-open,.navbar-fixed-top,.navbar-fixed-bottom').css('marginRight',$(window).width()-$winWidth)
        }
    });
    e(document).on('hidden.bs.modal', function () {
        $('body,.navbar-fixed-top,.navbar-fixed-bottom').css('marginRight',0)
    });

답에 함수 'e'가 무엇인지 명확히 할 수 있습니까?
— Michael Butler

1

이것은 Arany의 대답을 취하고 모달이 화면 높이보다 큰 경우 작동합니다.

function centerModal() {
    $(this).css('display', 'block');
    var $dialog = $(this).find(".modal-dialog");
    var offset = ($(window).height() - $dialog.height()) / 2;
    //Make sure you don't hide the top part of the modal w/ a negative margin if it's longer than the screen height, and keep the margin equal to the bottom margin of the modal
    var bottomMargin = $dialog.css('marginBottom');
    bottomMargin = parseInt(bottomMargin);
    if(offset < bottomMargin) offset = bottomMargin;
    $dialog.css("margin-top", offset);
}

$('.modal').on('show.bs.modal', centerModal);
$(window).on("resize", function () {
    $('.modal:visible').each(centerModal);
});

안녕하세요 @jetlej 왜 Arany의 답변을 편집하여 포함시키지 않습니까? 그의 코드에서 큰 버그를 해결했습니다.
— pcatre

@ pcatre-편집 내용을 제출할 수 있는지 몰랐습니다! 지적 해 주셔서 감사합니다
— jetlej

1

부트 스트랩 modal.js에 수직 모달 센터링을 추가하려면 Modal.prototype.show함수 끝에 이것을 추가했습니다 .

var $modalDialog = $('.modal-dialog'),
        modalHeight = $modalDialog.height(),
        browserHeight = window.innerHeight;

    $modalDialog.css({'margin-top' : modalHeight >= browserHeight ? 0 : (browserHeight - modalHeight)/2});

페이지 크기 조정 또는 그 안에있는 항목이 확장 / 축소되어 대화 상자의 높이가 한 번 표시되면 제대로 작동하지 않습니다.
— Dirbaio

0

Modal을 Verical Align All All 대화 상자로 만들려면

/* 노트:

1. selector를 할당 할 필요가 없어도 문서에서 모든 모달을 찾아 세로 가운데로 만듭니다.

2. 중간에있는 특정 모달을 피하기 위해 클릭 이벤트에서 선택자가 아님

* /

 $( "[data-toggle='modal']" ).click(function(){
     var d_tar = $(this).attr('data-target'); 
     $(d_tar).show();   
     var modal_he = $(d_tar).find('.modal-dialog .modal-content').height(); 
     var win_height = $(window).height();
     var marr = win_height - modal_he;
     $('.modal-dialog').css('margin-top',marr/2);
  });

밀라노 판 디아에서


0

모달을 중심으로하는이 간단한 스크립트를 사용하십시오.

원하는 경우 기능을 일부 모달로만 제한하도록 사용자 정의 클래스 (예 : .modal 대신 .modal.modal-vcenter)를 설정할 수 있습니다.

var modalVerticalCenterClass = ".modal";

function centerModals($element) {
    var $modals;
    if ($element.length) {
      $modals = $element;
    } else {
    $modals = $(modalVerticalCenterClass + ':visible');
}
$modals.each( function(i) {
    var $clone = $(this).clone().css('display', 'block').appendTo('body');
    var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2);
    top = top > 0 ? top : 0;
    $clone.remove();
    $(this).find('.modal-content').css("margin-top", top);
});
}
$(modalVerticalCenterClass).on('show.bs.modal', function(e) {
    centerModals($(this));
});
$(window).on('resize', centerModals);

또한 모달의 수평 간격에 대한이 CSS 수정 사항을 추가하십시오. 모달에 스크롤을 표시하면 본문 스크롤이 Bootstrap에 의해 자동으로 숨겨집니다.

/* scroll fixes */
.modal-open .modal {
  padding-left: 0px !important;
  padding-right: 0px !important;
  overflow-y: scroll;
}

0

이 질문에 대한 또 다른 CSS 대답은 ...
이 솔루션은 CSS를 사용하여 원하는 효과를 얻는 동시에 모달 외부를 클릭하여 모달을 닫는 기능을 유지합니다. 또한 .modal-content팝업이 뷰포트 이상으로 커지지 않도록 높이와 너비 최대 값 을 설정할 수 있습니다 . 내용이 모달 크기 이상으로 커지면 스크롤이 자동으로 나타납니다.

참고 :
이 기능 .modal-dialog div이 제대로 작동하려면 권장되는 부트 스트랩을 생략해야합니다 (아무것도 깨지지 않는 것 같습니다). Chrome 51 및 IE 11에서 테스트되었습니다.

CSS 코드 :

.modal {
   height: 100%;
   width: 100%;
}

.modal-content {
   margin: 0 auto;
   max-height: 600px;
   max-width: 50%;
   overflow: auto;
   transform: translateY(-50%);
}

편집 :.modal-dialog 클래스를 사용하면 사용자가 모달 자체의 외부를 클릭하여 모달을 닫을 수 있는지 여부를 선택할 수 있습니다. 대부분의 모달에는 명시적인 '닫기'또는 '취소'버튼이 있습니다. 이 해결 방법을 사용할 때이 점을 명심하십시오.


0

너비와 높이로 모달을 중앙 집중화하는 가장 좋은 솔루션은 CSS 추가 및 모달 에서이 '중앙 집중'을 클래스로 추가하는 것입니다.

.centralize{
   position:absolute;
   left:50%;
   top:50%;

   background-color:#fff;
   transform: translate(-50%, -50%);
   width: 40%; //specify watever u want
   height: 50%;
   }

0

수직 중심 .modal-dialog-centered를 .modal-dialog에 추가하여 모달을 수직으로 가운데에 배치

데모 모달 시작

<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalCenterTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.