[英]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.