首页 > 解决方案 > 如何在保持标签纵横比的DIV中插入图像?

问题描述

我做了这个代码:

<div id="divImage" style="background-color: skyblue;height: 200px;">
        <div style="background-color: red;width: 8%;height: 60px;margin-left: 20px; position: relative;top:50%;margin-right: auto;transform: translateY(-50%);"></div>
        <div style="background-color: red;width: 8%;height: 60px;margin-right: 20px; position: relative;top:50%;margin-left: auto;transform: translateY(-150%);"></div>
    </div>

divImage我需要在宽度为 100%的图像中插入图像。为此,divImage高度必须不固定(height: 200px;)。我的目的是让它divImage适应任何屏幕尺寸(以% 为单位)。

标签: css

解决方案


您可以使用其伪元素强制您的盒子保持纵横比。这里的前元素总是有一个特定的填充顶部,这使得盒子占据了相对于其宽度的高度,因为100%等式中的总是指容器的宽度。

.divImage {
    &:before {

      // Change this line to adjust the aspect ratio
      // 1px / 1px will for example give you a square box. 
      // The first value refers to the height-part
      padding-top: 5px / 10px * 100%; 

      content: "";
      width: 1px;
      margin-left: -1px;
      float: left;
      height: 0;
    }
    &:after { /* to clear float */
      content: "";
      display: table;
      clear: both;
    }
}

如果您想在覆盖框的 div 中使用图像,请添加以下内容:

.divImage {
   position: relative;
   img {
      position:absolute;
      width: 100%;//might not be necessary, just check if it works without 
      height: 100%;//might not be necessary, just check if it works without 
      object-fit:cover; //or contain if you dont want it to fill the container
   }
}

推荐阅读