首页 > 解决方案 > 使图像适合父级并在其上添加铭牌

问题描述

我正在尝试插入一些图像并在它们上面添加铭牌。图像可以是垂直的、水平的和方形的。它们是静态的并手动添加。

我的期望:

它应该是什么样子。蓝色是文章,父级,1000px 宽。红色框架是容器.art,橙色是img,黑色是span纯文本。

预期结果

到目前为止我所做的。

html:

<div class="art">
    <img src="./some/path">
    <span>Image name</span>
</div>

CSS(CSS):

.art {
        max-width: 75%;
        margin: 0 auto;
        position: relative;

        img {
            object-fit: contain;
            width: 100%;
            max-height: 80vh;
        }

        span {
            box-sizing: border-box;
            position: absolute;
            left: 0;
            width: 100%;
            bottom: 1rem;
            padding: 1rem;
            background-color: rgba(0,0,0,0.85);
        }
    }

问题:适用于长图像,不适用于高。铭牌贴在图像之外。

标签: htmlcss

解决方案


请检查此代码。这是您的解决方案。

为 Image 父级添加一个 DIV 并为此添加 CSS。

.art {
  max-width: 75%;
  margin: 0 auto;
  position: relative;
  text-align:center;
}
.art-container{
  display:inline-block;
  position:relative;
}

  img {
    object-fit: cover;
    height: 80vh;
    max-width:100%;
  }

  span {
    box-sizing: border-box;
    position: absolute;
    color:white;
    left: 0;
    width: 100%;
    bottom: 1rem;
    padding: 1rem;
    background-color: rgba(0,0,0,0.85);
  }
}
<div class="art">
  <div class="art-container">
  <img src="https://i.pinimg.com/originals/af/8d/63/af8d63a477078732b79ff9d9fc60873f.jpg">
  <span>Image name</span>
    </div>
</div>
 
<!--  https://cdn57.androidauthority.net/wp-content/uploads/2015/11/00-best-backgrounds-and-wallpaper-apps-for-android.jpg  -->


推荐阅读