【问题标题】:Why does this background extend beyond the image upon hover?为什么悬停时这个背景会超出图像?
【发布时间】:2013-04-01 03:27:03
【问题描述】:

我正在尝试在相当复杂的布局上创建悬停效果。悬停效果有效,但悬停时背景(或覆盖)会超出图像(我希望它与图像一样大)。

有谁知道这是为什么以及如何解决它?

HTML

<article>
    <div class="img-crop">
        <a href="#" class="title-anchor"><h2>Title</h2></a>
        <a href="#"><img src="http://bit.ly/gUKbAE" /></a>
    </div>
</article>

CSS

* {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
}

article {
    overflow: hidden;
}

.title-anchor {
    display: inline-block;
    position: absolute;
    overflow: hidden;
    z-index: 1;
    width: 100%;
    height: 100%;
}

.img-crop:hover .title-anchor {
    background: rgba(0,0,0,0.5);
}

.img-crop {
    display: inline-block;
    position: relative;
    overflow: hidden;
    max-width: 100%;
    margin: 0;
    padding: 0;
}

h2 {
    color: rgba(0,0,0,0);
    margin: 0;
    padding: 0;
    z-index: 2;
    line-height: 0;
    position: absolute;
    top: 50%;
    left: 0;
    width: 100%;
    text-align: center;
}

.img-crop:hover h2 {
    color: black;
}

也在这里:http://jsfiddle.net/kmjRu/39/

【问题讨论】:

  • 我不认为这是任何边距或填充,因为我已经禁用了它们并且效果仍然存在。
  • 你不是已经在stackoverflow.com/questions/15904693问过这个问题了
  • @xec,我解决了我之前的问题,但无法弄清楚这一点。在我看来,这是一个不同的问题,尽管在某种程度上是前一个问题的一部分。如果你愿意,你可以删除我之前的问题。

标签: html css image header hover


【解决方案1】:

只需添加

img {
display: block;
}

http://jsfiddle.net/kmjRu/41/

图片默认为replaced inline elements

【讨论】:

    【解决方案2】:

    你需要在通用 css 上添加这个:

    img { border: 0; vertical-align: top;}
    

    ...

    http://jsfiddle.net/Riskbreaker/kmjRu/43/

    【讨论】:

    • 图片会与文字的基线垂直对齐,导致底部有间距
    • NP!这已成为 html5 样板标准(垂直对齐):github.com/h5bp/html5-boilerplate/blob/master/css/main.css
    • 我想我更喜欢你的回答,因为它不需要我弄乱显示模式。不过,近距离通话,两者都有效。
    【解决方案3】:

    定义 .img-crop 的高度:hover 与 .img-crop img 相同。例如

    .img-crop:hover {
        background: rgba(0,0,0,0.5);
        height: 100px;
    }
    .img-crop img{height: 100px;}
    

    【讨论】:

      猜你喜欢
      • 2014-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2020-07-24
      • 1970-01-01
      • 2015-08-19
      相关资源
      最近更新 更多