html - 我该如何解决这个相对/绝对问题?
问题描述
我正在尝试将此文本放在图像上,但它不起作用!我已经验证了代码中的所有内容,从将 css 链接到代码中的错误,但没有找到任何东西。
.pai {
position:relative;
}
.filho {
position:absolute;
text-align:center;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="Estudos.css">
</head>
<body>
<div class="pai">
<img src="bgestudio.jpg" alt="">
<div class="filho">
<h1>Qualquer</h1>
</div>
</div>
</body>
</html>
解决方案
您需要使容器 div 与图像的宽度相同,然后文本 div 填充容器:
.pai {
position:relative;
display:inline-block; /* make this div as wide as the image - can be removed if the image is 100% width */
}
.filho {
position:absolute;
text-align:center;
left: 0;
right:0; /* left and right mean width will be 100%; */
top:50%;
transform: translateY(-50%); /* top 50 and translate mean it is vertically centered */
color:white;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="Estudos.css">
</head>
<body>
<div class="pai">
<img src="https://www.fillmurray.com/200/300" alt="">
<div class="filho">
<h1>Qualquer</h1>
</div>
</div>
</body>
</html>
推荐阅读
- javascript - 函数内部的 JavaScript 数学不起作用
- sql - 如何制作一条只带来与提供的两个参数匹配的记录的 SQL 语句?
- angular - angular 5 i18n - 能够在模板外使用翻译字符串
- python - 在矩阵中找到具有相邻字母的最长路径
- github - github - 查找具有空描述的拉取请求
- azure-ad-b2c - 身份验证与授权?
- python - PyQt5 弯曲 QSlider
- angular - 无法再使用 --reporters 选项启动 ng 测试
- javascript - 如何使用 moment.js 格式化未来的日期和时间?
- python - Pandas cumsum 与增长率