html - 保持 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>
解决方案
允许块级元素 ( .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>
推荐阅读
- c# - OpenXML改变整个文档的字体大小
- r - 在 R 的限制下联合两个数据集
- angular - 用 Angular 中的新请求替换现有函数调用
- javascript - 如何直接在脚本标签中制作 webpack 捆绑 js,而不是通过 src
- javascript - ChartJS 3.0 - 数字格式
- android - 由于在 Admob 控制台中未验证地址引脚,广告服务被禁用 - 在 Admob 仪表板控制台中没有验证地址引脚的选项
- javascript - 将 Enjoyhint 与 nextJS 一起使用
- java - 不需要 JAXB 父类标记
- c# - Revit API 获取门几何图形周围的边界框(不包括秋千)
- python - 循环访问外部文件时调用函数