css - z-index 和相对位置

标签 css css-position

我有一个模式,它使用 JavaScript 显示/隐藏。

在模式中,将使用 JavaScript 插入图像。同样在图像上将存在一个 div 元素,它将模拟裁剪(获取图像的坐标)。

我在使图像保持在模态裁剪下方时遇到问题。 modal-crop 并且图像需要位于 modal-area 的中心。

我不能使用 grid 或 flex,因为我需要支持 IE9。

.modal {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1050;
  display: none;
  overflow: hidden;
  outline: 0;
}

.modal-area {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 50%;
  height: 50%;
  transform: translate(-50%, -50%);
  margin: 0 auto;
  padding: 30px;
  background-color: blueviolet;
  border-radius: 4px;
  box-shadow: 0 0 50px black;
  overflow: hidden;
}

.modal-area img {
  margin-left: auto;
  margin-right: auto;
}

.modal-crop {
  position: relative;
  background-color: aliceblue;
  left: 0;
  right: 0;
  top: 0;
  margin-left: auto;
  margin-right: auto;
  width: 200px;
  height: 200px;
  opacity: 0.2;
  z-index: 2;
}
<div class="modal">
  <div class="modal-area">
    <div class="modal-crop"></div>
    #img will be inserted here using Javascript#
  </div>
</div>

enter image description here

最佳答案

你的图片需要绝对像这样定位:

.modal {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1050;
  overflow: hidden;
  outline: 0;
  min-height: 300px;
}

.modal-area {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 50%;
  height: 50%;
  transform: translate(-50%, -50%);
  margin: 0 auto;
  padding: 30px;
  background-color: blueviolet;
  border-radius: 4px;
  box-shadow: 0 0 50px black;
  overflow: hidden;
}

.modal-area img {
  margin-left: auto;
  margin-right: auto;
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
}

.modal-crop {
  position: relative;
  background-color: aliceblue;
  left: 0;
  right: 0;
  top: 0;
  margin-left: auto;
  margin-right: auto;
  height: 100%;
  opacity: 0.2;
  z-index: 2;
}
<div class="modal">
  <div class="modal-area">
    <div class="modal-crop"></div>
    <img src="https://lorempixel.com/500/500/">
  </div>
</div>

关于css - z-index 和相对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46970221/

相关文章:

css - 如何修复顶部和底部边距折叠的问题?

html - 如何按基线垂直对齐文本和图像?

css - 覆盖 div 的绝对位置和高度 100% 不随滚动移动

html - 为什么我的 CSS 中的零填充会产生 'false' 边距?

javascript - 无法更改按钮颜色

css - 使用带有/背景图像的 Flexbox 和 div 的水平站点

html - 如何在 HTML5/CSS3 中创建一个推子并将任意元素放在前面(以引起注意)?

html - 如何使用 css 制作单个响应式背景图片?

html - 为什么页面底部没有裁剪我的绝对定位元素

css - 绝对定位 TR 和 TD 元件