2017-03-16 83 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>