首页 > 解决方案 > 保持 div 在调整大小时不重叠

问题描述

这些 div 有一个带有重叠文本的图像,它看起来像我想要的全尺寸。

但是,当我将大小调整为较小的移动尺寸时,文本会出现在图像的顶部,并且 div 会重叠。

我怎样才能做到这一点,以便在调整大小时将文本移到图像的底部,但最重要的是,容器不会重叠?

.container {
  position: relative;
  font-family: Arial;
  clear:both;
}

.text-block {
 clear:both;
  position: absolute;
  bottom: 30px;
  right: 10px;
  background-color: black;
  color: white;
  padding-left: 20px;
  padding-right: 20px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.container {
  position: relative;
  font-family: Arial;
  clear:both;
}

.text-block {
 clear:both;
  position: absolute;
  bottom: 30px;
  right: 10px;
  background-color: black;
  color: white;
  padding-left: 20px;
  padding-right: 20px;
}
</style>
</head>
<body>

<h2>Image Text Blocks</h2>
<p>How to place text blocks over an image:</p>

<div class="container">
  <img src="https://via.placeholder.com/250x150" alt="Nature" style="width:90%;">
  <div class="text-block">
    <h4>Nature</h4>
    <p>What a beautiful sunrise</p>
  </div>
  
</div>

<div class="container">
  <img src="https://via.placeholder.com/250x150" alt="Nature" style="width:90%;">
  <div class="text-block">
    <h4>Nature</h4>
    <p>What a beautiful sunrise</p>
  </div>
  
</div>


</body>
</html> 

标签: htmlcssresponsive-designresize

解决方案


允许块级元素 ( .text-blocks) 像小视口一样自然堆叠。然后使用媒体查询在首选断点之后应用绝对定位。

.container {
  font-family: Arial;
}

.container img {
  display: block;
  width: 100%;
}

.text-block {
  background-color: black;
  color: white;
  padding-left: 20px;
  padding-right: 20px;
}

@media ( min-width: 48em ) {
  .container {
    position: relative;
  }
  
  .container img {
    width: 90%;
  }
  
  .text-block {
    position: absolute;
    bottom: 30px;
    right: 10px;
  }
}
<h2>Image Text Blocks</h2>
<p>How to place text blocks over an image:</p>

<div class="container">
  <img src="https://via.placeholder.com/250x150" alt="Nature">
  <div class="text-block">
    <h4>Nature</h4>
    <p>What a beautiful sunrise</p>
  </div>
  
</div>

<div class="container">
  <img src="https://via.placeholder.com/250x150" alt="Nature">
  <div class="text-block">
    <h4>Nature</h4>
    <p>What a beautiful sunrise</p>
  </div>
  
</div>


推荐阅读