画面中央または画面上基準に表示するモーダルウィンドウの実装

モーダル内の内容が「 少ない 」場合と「 多い 」場合で、モーダルの表示位置を理想的な形にする
今回はプラグインを使用せずに、「 HTML・CSS・jQuery 」だけで実装しています。
以下デモでは同じコードを使用していますが、モーダル内の内容が「 少ない 」場合と「 多い 」場合でモーダルの表示位置が異なるのが特徴です。
モーダル内の内容が少ない場合
モーダルの内の内容に対して、画面上下の余白が空いている場合は、上下中央に表示されます。
モーダル内の内容が多い場合
モーダルの内の内容に対して、画面上下の余白が空いていない場合は、上基準に表示されます。
さらにはみ出した部分はスクロールして閲覧出来るのが特徴です。
今回使用したコードを追記します
上記で紹介した2つのデモは同じコードを使用しています。
HTML
<button class="open">OPEN</button>
<div class="container">
<div class="overlay"></div>
<div class="body">
<div class="main">
<div class="content">
<p class="text"><span>Lorem ipsum dolor sit amet</span></p>
<button class="close">CLOSE</button>
</div>
</div>
</div>
</div>
CSS
button{
max-width: 250px;
width: 100%;
height: 50px;
font-size: 16px;
font-weight: bold;
color: #fff;
background: #000;
border: none;
cursor: pointer;
}
button:hover{
opacity: .7;
}
.open{
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
.container{
display: none;
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
overflow: auto;
-webkit-overflow-scrolling: touch;
overflow-scrolling: touch;
}
.overlay{
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: rgba(0,0,0,0.5);
}
.body{
display: table;
width: 100%;
height: 100%;
}
.main{
display: table-cell;
text-align: center;
vertical-align: middle;
padding: 25px;
}
.content{
position: relative;
display: inline-block;
width: 70vw;
background: #fff;
padding: 25px;
box-sizing: border-box;
}
.text{
line-height: 1.8;
padding: 0 0 25px;
}
span{
display: inline-block;
text-align: left;
}
jQuery
$(function(){
var a = $('.container'),
b = $('.overlay'),
c = $('.open'),
d = $('.close');
//OPENをクリックでモーダルを開く
c.on('click',function(){
a.fadeIn();
});
//CLOSEをクリックでモーダルを閉じる
d.on('click',function(){
a.fadeOut();
});
//モーダルの周りをクリックで閉じる
b.on('click',function(){
a.fadeOut();
});
});