如何使图像适合 HTML 和 CSS 中 div 的宽度和高度?

问题描述 投票:0回答:1

我有一个宽度为100%的容器。然后我添加了 40% 的左 div 和 60% 的右 div,使其宽度为 100%。我向右侧 div 添加了一个图像,并希望它适合该 div 的宽度和高度,但它覆盖了右侧宽度的一半,但适合高度。

在我的 CSS 中,我将宽度和高度设置为 100%,以确保它覆盖整个宽度和高度。我还添加了 object-fit:cover 但仍然不起作用。请帮忙。

.right-section {
  position: relative;
  width: 60%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  border: 2px solid green;
}
.right-section .dashboard-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: -1;
}
<div class="right-section">
  <img src="https://placehold.co/600" alt="Dashboard Image" class="dashboard-image" />
  <div class="info-box">
    <h2>Customer Management</h2>
    <p>Manage all customers from individual customers to corporate or group customers.</p>
  </div>
</div>

javascript html css
1个回答
0
投票

我添加了 .container 来帮助显示答案。 出于演示目的,.container 上的高度任意设置为 75vh

.info-box 上的“display: flex”以允许居中(假设您愿意)

.info-box 上的“位置:绝对”,因此它允许图像作为背景

这段代码似乎对我有用:

.container {
        display: flex;
        position: relative;
        width: 100%;
        height: 75vh;
        background-color: lightblue;
    }
    
.left-section {
    display: flex;
    background-color: pink;
    width: 40%;
        height: 100%;
    flex-direction: column;
  justify-content: center;
  align-items: center;
    }
    
.right-section {
  position: relative;
  width: 60%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  border: 2px solid green;
}
.right-section .dashboard-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
    .info-box {
        display: flex;
        flex-direction: column;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: auto;
        text-align: center;
        align-self: center;
    }
<div class="container">
 <div class="left-section">
     
 </div>

 <div class="right-section">
  <img src="https://placehold.co/600" alt="Dashboard Image" class="dashboard-image" />
  <div class="info-box">
    <h2>Customer Management</h2>
    <p>Manage all customers from individual customers to corporate or group customers.</p>
  </div>
</div>

</div>

© www.soinside.com 2019 - 2024. All rights reserved.