当我在图像上盘旋时,该图像上会出现一些文字。然而,在对其进行集中化之后,定位出现了问题,文本标题显示在图像的左侧,它也没有居中。
下面是我的代码,其中包含在互联网上找到的几段代码。
这是我的HTML:
<div class="col-md-3">
<p class="caption">
<img class="profile_pic" src="img/spiropoulos.jpg" alt="spy" />
<span>Rainbow and Tree</span>
</p>
</div>
CSS:
div.clear {
clear: both;
}
p.caption {
display: block !important;
position: relative !important;
}
p.caption img {
position: absolute !important
}
p.caption span {
background: #000;
background: rgba(0,0,0,0.8);
color: white !important;
display: none;
padding: 5px 10px !important;
text-align: center;
position: absolute !important;
bottom: 0 !important;
left: 0 !important;
width: 100% !important;
}
p.caption span big {
font-weight: bold;
}
.profile_pic{
height: 160px;
width: 200px;
}
和JS:
// this is to center the image
$("p.caption>img").each(function(i, img) {
$(img).css({
position : "relative",
left : ($(img).parent().width() / 2) - ($(img).width() / 2)
});
});
// this is for the caption
// For each instance of p.caption
$("p.caption>div").each(function() {
$(this)
// Add the following CSS properties and values
.css({
// Height equal to the height of the image
"height" : $(this).children("img").height() + "px",
// Width equal to the width of the image
"width" : $(this).children("img").width() + "px"
})
// Select the child "span" of this p.caption
// Add the following CSS properties and values
.children("span").css(
// Width equal to p.caption
// But subtract 20px to callibrate for the padding
"width", $(this).width() - 20 + "px")
// find the <big> tag if it exists
// And then add the following div to break the line
.find("big").after('<div class="clear"></div>');
// When you hover over p.caption
$("p.caption>div").hover(function() {
// Fade in the child "span"
$(this).children("span").stop().fadeTo(400, 1);
}, function() {
// Once you mouse off, fade it out
$(this).children("span").stop().delay(600).fadeOut(400);
});
// End $(this)
});
预期结果如下:http://css-plus.com/examples/2010/05/how-to-create-an-image-caption-with-jquery/
答案 0 :(得分:1)
尝试使用css
:hover
,:after
p:hover:after {
content:"Rainbow and Tree";
font-family:Arial;
font-size:11px;
background:#000;
text-align:center;
position:relative;
color:#fff;
top:-4px;
left:-99px;
z-Index:1;
opacity:.75;
}
&#13;
<p>
<img src="http://lorempixel.com/100/100/nature" />
</p>
&#13;
答案 1 :(得分:1)
div {
display: inline-block;
position: relative;
}
div img {
vertical-align: top;
}
div h2 {
position: absolute;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(255,255,255,0.5);
text-align: center;
margin: 0;
padding: 1.0em 0; /*optional*/
display: none;
}
div:hover h2 {
display: block;
}
Here is one way of display a caption over an image using CSS only.
<div>
<img src="http://lorempixel.com/400/200/nature" />
<h2>Some Caption Text</h2>
</div>