[英]Can't center the image inside of a full-screen overlay modal
我正在使用 HTML、CSS 和 Vanilla Javascript 的基本知識來處理我的第一個個人項目,我正在嘗試通過將其放入全屏覆蓋模式來放大頁面上的圖片。
我設法讓它變大並通過單擊再次恢復到原始大小,但我無法讓它在模態中居中。 有時它以扭曲的高度接觸頂部和底部,有時圖像和模態都太小,有時它位於屏幕的左側或任何其他角落。
我希望它占據用戶屏幕的 70% 或 80% 左右,並且垂直和水平居中,包括在移動設備上。
我能做到的最好的辦法是讓它的大小合適,不會讓它變形,但它會粘在桌面的左上角,比移動設備的中心高一點。 下面提供了代碼。
HTML
<main role="main">
<h1 class="h1-mapas">MAPAS DE SUBTE</h1>
<div class="main-div">
<div id="img-div" class="img-div">
<img id="mapa-img" class="mapa-img" src="/images/mapa-subte.jpg" alt="Mapa de subte con todas las líneas y paradas">
</div>
</div>
<div id="theModal" class="modal">
<img class="modal-img" id="modalImg">
</div>
</main>
CSS
.modal {
display: none;
position: absolute;
z-index: 1;
background-color: rgba(255,255,255,0.9);
left: 0;
top: 0;
overflow: auto;
width: 100%;
height: 100%;
}
.modal-img {
margin: 0 auto;
width: 75%;
animation-name: zoom;
animation-duration: 0.6s;
}
@keyframes zoom {
from {transform: scale(0.1)}
to {transform: scale(1)}
}
JS
const modal = document.getElementById("theModal")
const img = document.getElementById("mapa-img")
const modalImage = document.getElementById("modalImg")
img.onclick = function() {
modal.style.display = "block"
modalImage.src = this.src
}
modal.onclick = function() {
modal.style.display = "none"
}
我還嘗試在 CSS 的 .modal 中添加和/或刪除這些,以及在 JS 中將模態顯示更改為 flex 並在 CSS 中居中對齊圖像(然后它會因高度而失真),但從未設法讓它正確。
top: 50%;
transform: translate(-50%, -50%);
width: 100%;
height: 100%;
非常感謝大家的幫助!
我使用display: grid
作為模態和place-itmes: center
作為 CSS 的一部分。
const modal = document.getElementById("theModal") const img = document.getElementById("mapa-img") const modalImage = document.getElementById("modalImg") img.onclick = function() { modal.style.display = "grid" /* Changed */ modalImage.src = this.src } modal.onclick = function() { modal.style.display = "none" }
#mapa-img { width: 25%; height: auto; }.modal { display: none; position: absolute; z-index: 1; background-color: rgba(255, 255, 255, 0.9); left: 0; top: 0; overflow: auto; width: 100%; height: 100%; place-items: center; /* Added */ }.modal-img { margin: 0 auto; width: 75%; animation-name: zoom; animation-duration: 0.6s; } @keyframes zoom { from { transform: scale(0.1) } to { transform: scale(1) } }
<main role="main"> <h1 class="h1-mapas">MAPAS DE SUBTE</h1> <div class="main-div"> <div id="img-div" class="img-div"> <img id="mapa-img" class="mapa-img" src="https://picsum.photos/300/200" alt="Mapa de subte con todas las líneas y paradas"> </div> </div> <div id="theModal" class="modal"> <img class="modal-img" id="modalImg"> </div> </main>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.