html - 当我尝试将 2 个 CSS 规则集压缩为一个时,为什么我的字幕无法正常工作?
问题描述
所以,我刚开始用 HTML、CSS 和 JS 制作我的第一个网页,我想要一个黑色半透明方块在图像上,里面有文本。
在 CSS 中,我有一个遇到问题的规则集:“.caption”。这个类是一个 div 的类,你会看到有 2 个规则集被注释掉了。
问题是,当我取消注释它们并评论“.caption”时,页面可以完美运行。但是当用下面的方式评论时,它根本不起作用,文本出现在图像下方,没有格式。
我知道我不必更改它,但我想同时定位两个文本元素,并且它们周围的灰色框是正方形,而不是 5 边形状(下面的链接图片)和更清晰的代码. 有办法吗?文本在它自己的类和 div 中,对吧?
这是代码:
.teamworkImage {
width: 100%;
height: 600px;
}
/*.caption h1 {
position: absolute;
bottom: 500px;
font-family: 'Segoe UI';
color: rgb(255, 255, 255);
font-size: 60px;
background-color: rgba(0,0,0,0.7);
}
.caption p {
position: absolute;
bottom: 360px;
font-family: 'Segoe UI';
color: rgb(255, 255, 255);
font-size: 20px;
width: 200px;
background-color: rgba(0,0,0,0.7);
padding: 10px;*/
}
.caption {
position: absolute;
bottom: 500px;
font-family: 'Segoe UI';
color: rgb(255, 255, 255);
font-size: 40px;
background-color: rgba(0,0,0,0.7);
}
<div id = 'main'>
<div class = 'image'>
<img src = 'img/teamwork.jpg'
class = 'teamworkImage'>
<div class = 'caption'>
<h1>THIS IS TEAMWORK</h1>
<p>
Our team-building activites help you form new friends, face fears, and - most important of all - have fun.
</p>
</div>
</div>
</div>
解决方案
主要的问题是你有一堆绝对定位的东西。这很危险,应该谨慎使用。另外,请仔细考虑您绝对定位在哪个元素中。该元素本身不得具有静态(默认)定位。
.image {
position: relative; /* <-- set an ancestor as the container */
}
.image > img {
width: 100%;
}
.caption h1 {
font-family: 'Segoe UI';
color: rgb(255, 255, 255);
font-size: 60px;
}
.caption p {
font-family: 'Segoe UI';
color: rgb(255, 255, 255);
font-size: 20px;
background-color: rgba(0, 0, 0, 0.7);
padding: 10px;
}
.caption {
position: absolute; /* <-- just this box is absolutely-positioned */
bottom: 50px;
font-family: 'Segoe UI';
color: rgb(255, 255, 255);
font-size: 40px;
background-color: rgba(0, 0, 0, 0.7);
}
<div id='main'>
<div class='image'>
<img src='http://placehold.it/800x500' class='teamworkImage'>
<div class='caption'>
<h1>THIS IS TEAMWORK</h1>
<p>
Our team-building activites help you form new friends, face fears, and - most important of all - have fun.
</p>
</div>
</div>
</div>
推荐阅读
- java - 如何使用 getExternalStorageDirectory() 从内部存储加载多首歌曲
- c# - Xamarin 在蓝牙打印机中打印图像
- php - Tesseract - 检测图像的小字体并转换为文本
- wordpress - 如何在 Woocommerce 中的购物车按钮附近添加“显示详细信息”按钮
- java - 为什么 gradlew 在不同的机器上构建不同的 jar?
- c++ - 双向链表函数c++(作业)
- vba - VBA:筛选重复项时对象“_Worksheet”的运行时1004方法“范围”错误
- xamarin - 光标到达最后一个文本位置时改变粗细
- hybris - 在 Hybris 中插入图像
- ruby-on-rails-5 - devise_token_auth 未定义方法“create_token”问题