我有一个基于百分比的数字。在那个盒子里,我有一个透明背景的图像。我需要将其水平居中,并将其固定在容器的底部,同时让顶部从容器中脱出(见图)。
我可以使用绝对定位将其固定在底部并突破顶部,但我无法将其置于中心位置。当我不知道图像的宽度和容器的宽度是否灵活时,有没有办法做到这一点?显示:表有可能吗?
我的代码:
<figure class="feature">
<a href="#">
<img src="image" />
<p class="title-bar">Caption</p>
</a>
</figure>
.figure { position: relative; width: 50%; }
.figure img { position: absolute; bottom: 0; }
答案 0 :(得分:3)
您可以使用纯CSS执行此操作,但您需要两个额外的div来保存和定位元素。
这是CSS:
.featureHolder {
position: relative;
/* height can be anything */
height: 200px;
}
.feature {
margin: 0;
overflow: visible;
/* width can be anything */
width: 60%;
height: 100px;
background: #cccccc;
position: absolute;
bottom: 0;
}
.imageHolder {
text-align: center;
width: 100%;
position: absolute;
bottom: 0;
}
img {
margin-bottom: -5px;
}
这是HTML:
<div class="featureHolder">
<figure class="feature">
<div class="imageHolder">
<a href="#">
<img src="img" />
</a>
</div>
<a href="#" class="title-bar">Caption</a>
</figure>
</div>
标题也可以放在与图像相同的标签内,但在这个例子中它被分开,所以我不必弄乱它。
这是JSFiddle中的演示 - 给.feature任何宽度,img仍应居中。 (顺便说一下你的CSS不对 - 它应该是'figure'或'.feature',但不能是'.figure',因为图是一个带有类名'feature'的元素。)
答案 1 :(得分:3)
请检查这个小提琴,有2个变体来居中图像
标记是相同的
<figure>
<a href="">
<img src="http://placekitten.com/200/300" alt="" />
</a>
</figure>
两种方法的一般风格
img{
vertical-align: bottom;
}
第一个变种
figure{
position: relative;
width: 50%;
height: 300px;
background: #cad;
}
figure a{
position: absolute;
bottom: 0;
left: 50%;
}
figure img{
position: relative;
left: -50%;
}
第二个
figure{
position: relative;
width: 50%;
height: 300px;
background: #cad;
}
figure a{
position: absolute;
width: 100%;
left: 0;
bottom: 0;
text-align: center;
}
答案 2 :(得分:0)
基本上你需要做左:50%然后左边缘: - 无论图像的宽度是多少。这将把它放在你的相对div中心。我的例子假设您不知道图像的宽度。
http://jsfiddle.net/rVRT4/2/ http://jsfiddle.net/rVRT4/2/embedded/result/
$(document).ready(function(){
var width = $(".figure img").width();
$(".figure img").css("margin-left", -(width/2));
});
.figure { position: relative; width: 50%; height: 500px;}
.figure img { position: absolute; bottom: 0; left:50%;}
<div class="figure">
<a href="#">
<img src="http://i.stack.imgur.com/4TtEY.jpg" />
<p class="title-bar">Caption</p>
</a>
</div>