html - 图像右上角的 CSS 按钮(图库)
问题描述
我正在尝试将关闭按钮 (x) 定位到图像的右上角。
那就在我页面的页脚之前:
<div class="modal" id="modal">
<span class="close" id="close">✖</span>
<img class="modal-content" id="modal-content">
</div>
我如何显示模态:
function showModal(name) {
modal.style.display = "block";
modalImg.src = document.getElementById(name).src;
}
这是我的样式:
/* Background when image is shown */
#modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(119, 119, 119); /* Fallback color */
background-color: rgba(119, 119, 119, 0.9); /* Black w/ opacity */
}
/* Image */
#modal-content {
/* Horizontally center image */
margin: auto;
/* Sizing */
display: block;
max-width: 90%;
max-height: calc(100vh * 0.5);
width: auto;
/* Zoom (image gets bigger) on open */
animation-name: zoom;
animation-duration: 0.6s;
/* Style */
border: 10px solid #ffffff;
box-shadow: rgba(0, 0, 0, 0.54) 0px 0px 7px 4px;
/* Vertically center image */
position: relative;
top: 40%;
transform: translateY(-40%);
}
@keyframes zoom {
from {
transform: scale(0)
}
to {
transform: scale(1)
}
}
/* Close Button */
#close {
/* Position */
position: absolute;
top: 10px;
right: 10px;
/* Style */
color: #ffffff;
font-size: 20px;
font-weight: bold;
transition: 0.3s;
background-color: #000000;
border: 3px solid #ffffff;
box-shadow: rgba(0, 0, 0, 0.5) 0px 0px 25px 3px;
/* Makes the Button round */
border-radius: 50%;
padding-left: 7px;
padding-right: 7px;
padding-bottom: 3px;
}
/* Change cursor when pointing on button */
#close:hover,
#close:focus {
text-decoration: none;
cursor: pointer;
}
/* 100% image width on smaller screens */
@media only screen and (max-width: 700px) {
.modal-content {
width: 100%;
}
}
问题是
position: absolute;
top: 10px;
right: 10px;
将关闭按钮定位在页面的右上角,而不是图像的右上角。
我该如何解决?
解决方案
close
它相对于最近定位的祖先定位的元素,在您的情况下是modal
div 而不是modal-content
(如您所愿)。
我建议您将“按钮”modal-content
和close
“按钮”包含在(相对)div 中,如下所示:
<div class="modal" id="modal">
<div id='modal-content' class='modal-content">
<span class="close" id="close">✖</span>
<img> //make img height/width to 100%
</div>
</div>
这应该将关闭按钮定位在绝对 div 的右上角和该 div 内的图像。
如果没有出现关闭按钮,请确保它z-index
比图像高。
我做了一个codepen:https ://codepen.io/jpaulet/pen/RwGxpxy
推荐阅读
- vba - VBA 正在跳过命名范围线
- leaflet - 将 DEM 转换为保持像素值的 PNG 切片?
- css - 删除固定页脚和主要实现之间的空白
- php - 如何更新 laravel 中的用户表?
- angular - 使用指令对 *ngFor 中使用的对象数组进行排序
- polymer - 使用 Paper-Input 时 Polymer 3.0 未捕获的 DOM 异常
- wordpress - Wordpress 在哪里保留图像 ID 和图像源之间的关系?
- html - 使 iframe 适合父 div
- bootstrap-4 - 为什么 bootsrtap 4 不能正常工作?
- java - 保存我的 PNG 会破坏 alpha 通道