首页 > 解决方案 > 当我尝试将 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>

使用下面的 CSS 代码 在此处输入图像描述

CSS 的注释部分未注释,“.caption”规则集已注释 在此处输入图像描述

演示小提琴

标签: htmlcssimage

解决方案


主要的问题是你有一堆绝对定位的东西。这很危险,应该谨慎使用。另外,请仔细考虑您绝对定位在哪个元素中。该元素本身不得具有静态(默认)定位。

.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>


推荐阅读