如何将绝对定位的 div 居中放置在固定定位的 div 中间

6
我已经设置了一个弹出框来显示照片,当我点击小照片时,会在弹出框中显示大照片。弹出框具有position: fixed;,而弹出框内容具有position: absolute; 我可以使用margin: auto; left: 0; right: 0;将其居中,但是宽度会延伸到最左边和最右边,我希望弹出框的宽度与其中的照片或弹出框内容相同。 我的代码:
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding: 30px;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */

}

.modal-content {
    background-color: #fefefe;
    position: absolute;
    top: 50px;
    margin-bottom: 30px;
    margin: auto;
    border: 1px solid #888;
}

.modalimg {
    position: relative;
    text-align: center;
}

.modalimg  img{
    max-width: 100%;
    max-height: 400px;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0; 
    position: relative;
    box-shadow: 0 0 20px rgba(0,0,0,0.4); 

}

现在可能有点混乱,但我已经尝试了很多不同的方法,却没有成功。


你好,能否提供JSFiddle链接或代码片段? - krychuq
你可以使用transform:translate() - Carl Binalla
https://jsfiddle.net/e5smw1s9/18/ - Mathias Hermansen
5个回答

9

当我要使绝对定位的元素居中时,我使用以下代码,这个方法一直适用于我的项目:

.absolute-center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

3
这里是您需要的,请注意:

.element {
  position: absolute;
  top: 15px;
  z-index: 2;
  width: 40%;
  max-width: 960px;
  min-width: 600px;
  height: 60px;
  overflow: hidden;
  background: #fff;
  margin: 0 auto;
  left: 0;
  right: 0;
  background: red;
  color: #fff;
  text-align: center;
}
<div class="element">
  text..
</div>


1

如何将绝对定位的div居中显示 left: 0; right: 0; text-align: center; 这样可以使div在中间对齐。


1
如果我没记错的话,text-align 在绝对定位的元素上不起作用。 - Carl Binalla
它有效。由于这里的宽度是100%,我假设您想要将内部元素居中对齐?如果您想要将div本身居中对齐,您可以减少百分比宽度。https://codepen.io/shshaw/full/gEiDt - user1705314

1
这里是一种可能的解决方案,它使用了以下方法:
  • 在内容容器(.modal-content)上使用绝对定位
  • 不在实际内容上使用absolute|fixed
内容容器(.modal-content)将随其内容增长。最后,使用transform: translate(-50%, -50%);将其移回中间位置:

.modal {
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.4);
}

.modal-content {
    border: 1px solid red;
    position: absolute;
    top: 50%;
    left: 50%;
    border: 2px solid red;
    transform: translate(-50%, -50%);
}
<div class="modal">
  <div class="modal-content">
    <img src="//placehold.it/200x200" alt="">
  </div>
</div>

演示

先试用再购买


1
.modal-content {
    background-color: #fefefe;
    position: absolute;
    top: 50px;
    left: 50px;
    right: 50px;
    bottom: 50px;
    border: 1px solid #888;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接