2017-03-16 86 views
1

我已经设置了一个照片模式,所以当我点击一张小照片时,我得到一张较大的照片,模态为position: fixed;,模态内容有position: absolute;我可以margin: auto; left: 0; right: 0;居中但随后的宽度变为一路左右,我想要的模式内容宽度是相同里面的照片或模态内容如何在一个固定div中居中放置一个绝对div

的内容我代码:

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

} 

它也许现在有点混乱,但我已经尝试ALO t不同的东西没有运气..

+0

嗨,你能提供的jsfiddle链接或剪断代码 – krychuq

+0

你可以使用'变换:翻译()' – Swellar

+0

https://jsfiddle.net/ e5smw1s9/18/ –

回答

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

你有没有试过这个? – Swellar

1

将绝对div对齐中心 left:0; right:0 text-align:center 这将使div居中对齐。

+1

如果我没有弄错,'text-align'将无法在绝对定位元素上工作。它的工作原理是 – Swellar

+0

。因为这里宽度我可以看到100%,我假设你想要中心内部元素?如果你想中心div本身,你可以减少宽度在百分比.https://codepen.io/shshaw/full/gEiDt – user1705314

1

这是一个使用一个可能的解决方案:内容容器上

  • absolute定位(.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>

演示

Try before buy

3

这是什么时,我中心的绝对定位的元素我用,这对我一直工作:

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

在这里,请

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