4

我正在尝试一种聪明的方法来处理网页的一部分,其中图像将被不同的图像(不同宽度,最大为 620px 宽)换出,并且文本标题绝对定位在它上面. 我希望文本根据图像的宽度而不是相对定位的容器的宽度来绝对定位。

我在想可能是背景图像,而不是图像本身,但是我必须处理它是一个带有背景图像的空 div 的事实,所以我必须硬编码一个高度,这是行不通的因为其中一些图像会比其他图像高。

你们能想到的任何解决方案都将不胜感激。谢谢!

4

4 回答 4

4

我不确定我是否 100% 关注,但这里是我认为你正在尝试做的事情。

使用相对位置创建容器,设置宽度和高度,并将溢出设置为隐藏:

.container-outer {
  position: relative;
  width: 200px;
  height: 200px;
  overflow: hidden;
}

接下来,在其中创建一个内部容器,其中包含 position: absolute

.container-inner {
  position: absolute;
}

最后,将覆盖文本样式创建为 100% 宽度并水平居中(或者您希望它定位)

.overlay {
  position: absolute;
  text-align: center;
  width: 100%;
  margin: 0;
}

这是带有示例的 jsfiddle:http: //jsfiddle.net/BGvca/1/

祝你好运!

于 2012-09-12T17:44:54.460 回答
1

我用更多的 CSS 提出了先前的答案

<div class="imageholder">
    <div class="caption">Simon &amp; Garfunkel</div>
    <img src="http://greenobles.com/data_images/simon-and-garfunkel/simon-and-garfunkel-03.jpg">
</div>​
.imageholder{
    position: relative;
    float: left;
}
.caption{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    font-family: Helvetica,sans-serif;
    font-size: 1em;
    background: rgba(0,0,0,0.5);
    color: #fff;
    padding: 1em 2em;
}

​ 参考jsFiddle

于 2012-09-12T17:42:36.053 回答
1

如果您使 div 包含图像inline-block,它的宽度将缩放到其内容的大小,即您的图像。

一旦容器的大小正确,您可以使用带有 的包装器将其他子元素(例如标题)居中,或者没有包装器,并且左右边距的text-align: center值为。auto

这是一个例子: http: //jsbin.com/uyajaw/3/edit(带有丑陋的边框和背景来显示东西在哪里)

单击图像以调整其大小并看到标题仍居中。

请注意,如果您的标题可能比您的图像大,它可能会扩大容器 div 的宽度,从而偏离中心对齐。您可以通过在标题上进行设置来避免这种情况position: absolute; left: 0; right: 0;,或者通过给它一个您知道将始终小于图像的宽度来避免这种情况。

于 2012-09-12T17:47:00.743 回答
0

I don't know if I'm over-thinking this, but here's a way to do it. If you specifically don't want to align the caption with the wrapper div, then you'll need to also account for the imagesLoaded event (jQuery plugin). Otherwise, you will either have an img width of 0 if not loaded, or you'll have the previously loaded img width in there (unless you go back to it).

Take a look at this Fiddle that shows a fixed width wrapper div and the caption centered on it.

于 2012-09-12T18:20:39.983 回答