使叠加容器的大小与图像内部相同

时间:2016-07-12 19:59:45

标签: html css image overlay

有图像。在此示例中,它有width: 320px;height: 200px;叠加层可以正常使用:

.overlay-content {
  width: 320px;
  height: 200px;
  ...
}

但我无法设置图片的声明,例如

img {
  ...
}

有没有办法在不知道.overlay-content中的宽度和高度且没有为<img>设置声明的情况下执行此操作?

这是一个JSFiddle,以及相应的示例:

img {
  /* You can't do anything here */
}
.overlay {
  position: relative;
  margin: 50px;
}
.overlay-content {
  position: absolute;
  /* This you don't know */
  width: 320px;
  /* This you don't know */
  height: 200px;
  top: 0;
  background: grey;
  opacity: 0;
  transition: opacity .3s ease;
}
.overlay-content div {
  position: absolute;
  height: 100%;
  width: 0%;
  overflow: hidden;
  right: 0;
  background: orange;
  transition: width .3s ease-in-out;
}
.overlay-content div ul {
  display: block;
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  list-style-type: none;
}
.overlay-content div ul li {
  position: relative;
  height: 33.3333%;
  width: 0%;
  text-align: center;
  overflow: hidden;
  transition-property: width;
  transition-delay: .2s;
  transition-duration: .5s;
  transition-timing-function: ease;
}
.overlay-content div ul li span,
.overlay-content div ul li a {
  position: absolute;
  display: block;
  width: 100%;
  top: 50%;
  margin-top: -25px;
  font-size: 22px;
  height: 50px;
  line-height: 50px;
  vertical-align: middle;
  color: yellow;
}
.overlay:hover > .overlay-content {
  opacity: 1;
}
.overlay:hover > .overlay-content div {
  width: 50%;
}
.overlay:hover > .overlay-content div ul li {
  width: 100%;
}
<div class="overlay">
  <img src="http://placehold.it/320x200" />
  <div class="overlay-content">
    <div>
      <ul>
        <li><a href="#">First</a>
        </li>
        <li><span>Second</span>
        </li>
        <li><span>Third</span>
        </li>
      </ul>
    </div>
  </div>
</div>
<div class="overlay">
  <img src="http://placehold.it/320x200" />
  <div class="overlay-content">
    <div>
      <ul>
        <li><a href="#">First</a>
        </li>
        <li><span>Second</span>
        </li>
        <li><span>Third</span>
        </li>
      </ul>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

您可以将叠加设置为display:inline-block;display:table;,以使其大小与图片相同,因为.overlay-content被设置为绝对位置&#39;超出了正常的内容流程。

.overlay {
  position: relative;
  display: inline-block;
  ...
}

叠加内容为:

.overlay-content {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  ...
}

<强> jsFiddle