首页 > 解决方案 > 垂直居中弹出模式,高度设置为自动

问题描述

我有一个模式,它包含从数组中获得的一系列列表项,如下所示:

$.each(newsArr, function(i) {
  $('#allNewsDiv').append('<div class="all-news-item"><img src="https://dl.dropbox.com/s/r8nu1zb2gpzd92k/Ball%20Icon.png" alt="" style="float:left; margin-right:10px; position: relative; top: 2px;" width="20" height="20"><div class="all-news-item-text">' + newsArr[i] + '</div></div>');
});

最初隐藏的模态可以随数组中的项目数而变化。我希望它垂直居中,但是当元素的高度可以变化时,我该怎么做?

到目前为止,我已经尝试使用 jQuery函数测量 div.outerHeight(true)的高度并设置其高度。没运气!每个的高度似乎都被忽略了,返回的高度只是边距的总和。以下 CSS 用于模态:#allNewsDiv.css.all-news-item

#overlay {
  position: fixed;
  display: none;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #515151;
  opacity: 0.5;
  z-index: 99;
}

#allNewsDiv {
  width: 500px; 
  height: auto;
  position: fixed;
  top: 50%;
  left: 50%;
  margin-left: -275px;
  /*margin-top: ? */
  padding: 25px;
  background-color: #fff;
  border-radius: 8px;
  color: #000;
  /*text-align: center;*/
  box-shadow: 0 0 10px 5px #000;
  z-index: 100;
  display: none;
}

.all-news-item {
  font-family: 'Play';
  color: #000;
  margin: 10px;
}

我也尝试过使用transform: translate (50vw,50vh)and transform-origin: 50% 50%,但是,再一次,没有运气!

这是一个小提琴(一些样式已经改变,但大致相同):

https://jsfiddle.net/shaneswebdevelopment/1d6snzoq/

标签: jquerycssmodal-dialog

解决方案


推荐阅读