代码之家  ›  专栏  ›  技术社区  ›  XingD123

如何将带有文本的背景放置在另一个没有HTML的背景图像上

  •  0
  • XingD123  · 技术社区  · 10 年前

    我制作了一个带有复选框的表单作为森林图像。我需要在森林checbox图像上放置另一个透明背景和来自html参数(数据森林)的文本,但我只能通过CSS来完成。我尝试了很多解决方案,但没有一个能正常工作。有人知道吗?

    最终效果 悬停时 :

    enter image description here

    Js小提琴: https://jsfiddle.net/ac9z8sgd/

    HTML语言

    <form action="action" method="get">
      <input type="hidden" name="test" value="test" />
      <ul>
        <li><input id="checkbox" type="checkbox" name="forest_type" value="forest_1"><label for="checkbox_forest" data-forest="Estern forest">Forest 1</label></li>
      </ul>
      <button type="submit">Submit</button>
    </form>
    

    CSS公司

    /* Default check button */
    #checkbox + label {
    
      background: url('http://i.imgur.com/Ds7gh7b.jpg?1');
      background-repeat: no-repeat;
      height: 250px;
      width: 250px;
      padding: 15px 15px;
      display: inline-block;
      position: relative;
    }
    /* Hover action */ 
    #checkbox + label[data-forest]:hover {
      background: rgba(0,0,0,0.8);
      content: attr(data-forest);
      display: inline-block;
      font-size: 20px;
      color: white;
      position: relative;
    } 
    
    2 回复  |  直到 10 年前
        1
  •  0
  •   Paulie_D    10 年前

    使用伪元素。

    /* Default check button */
    
    #checkbox + label {
      background: url('http://i.imgur.com/Ds7gh7b.jpg?1');
      background-repeat: no-repeat;
      height: 275px;
      width: 184px;
      display: inline-block;
      position: relative;
    }
    /* Hover action */
    
    #checkbox + label[data-forest]:hover::after {
      background: rgba(0, 0, 0, 0.8);
      content: attr(data-forest);
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 50%;
      font-size: 20px;
      color: white;
      display: flex;
    }
    <form action="action" method="get">
      <input type="hidden" name="test" value="test" />
      <ul>
        <li>
          <input id="checkbox" type="checkbox" name="forest_type" value="forest_1">
          <label for="checkbox_forest" data-forest="Estern forest">Forest 1</label>
        </li>
      </ul>
      <button type="submit">Submit</button>
    </form>

    JSfiddle with Transitions

        2
  •  0
  •   Little Santi    10 年前

    我的建议:

    label[data-forest]:hover:before {
      background: rgba(0,0,0,0.8);
      content: attr(data-forest);
      font-size: 20px;
      color: white;
      margin-top: 240px;
      margin-left: -15px;
      position: absolute;
      width: 100%;
      text-align: center;
    } 
    

    顺便说一句:对于可感知的透明度来说,0.8可能太高了。我会让它变成0.4。

    推荐文章