【问题标题】:Background hidden when overlaying header with negative top margins用负上边距覆盖标题时隐藏背景
【发布时间】:2014-06-10 16:44:12
【问题描述】:

我正在尝试将标题叠加到图像上。但是背景隐藏在图像下方。 为什么会这样?

http://jsfiddle.net/YRDFB/

<div class="header">
<img width="100%" height="200px"  src="/path/to/image.jpg" />
<h1>Header Title</h1></div>


h1 {
    background: rgba(67,67,67,0.8);
    margin-top: -3em;
}

【问题讨论】:

    标签: html css image margin background-color


    【解决方案1】:

    你在找这个Updated Fiddle

    h1 {
    background: rgba(67, 67, 67, 0.8);
    position:relative;
    z-index:9;
    display:block;
    width:100%;
    padding:0;
    color:#fff;
    margin-top:-43px;
    }
    

    【讨论】:

      【解决方案2】:

      我们这里有 2 个解决方案:

      1. 使用display:inline-block 并为您的h1 设置width:100%,同时在img 上使用否定的margin-bottom

        h1 {
          background: rgba(67,67,67,0.8);    
          display:inline-block;
          width:100%;
        }
        img {
          margin-bottom:-4em;
        }
        

        Demo 1.

      2. 使用 position:relative 作为 img 并为其设置 z-index:-1

        h1 {
          background: rgba(67,67,67,0.8);    
        }
        img {
          margin-bottom:-4em;
          position:relative;
          z-index:-1; 
        }
        

        Demo 2.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-19
        • 1970-01-01
        • 2020-01-10
        • 2015-01-27
        相关资源
        最近更新 更多