我试图将DIV水平居中在另一个有图像的DIV中。我可以让它只与父\子DIV一起工作,但是一旦我添加图像,事情就会变得疯狂。
这是我尝试过的。理想情况下,我希望box2在外部DIV \图像的底部居中,但在图像的顶部,无论使用什么尺寸的图像。
请参阅示例http://i60.tinypic.com/mbmqzr.jpg
连连呢?
https://jsfiddle.net/uz0L5oow/2/
CSS
#box1{
position:relative;
display:inline-block;
width: 200px;
height: 200px;
}
#box2{
width:50px;
margin: 0 auto;
background-color: yellow;
}
HTML
<div id="box1">
<img src="http://i44.tinypic.com/2j4akqb.jpg"/>
<div id="box2">box</div>
</div>
答案 0 :(得分:1)
试试这个。我所做的就是取出外部div上的宽度(如果你设置了两者,你的最终尺寸可能会因img而异)。然后将img设置为100%的高度。不要设置两个...只有一个和另一个将遵循img的保持比率。然后最后为底部div我把它放在绝对的底部0和右边一个d左边0然后边缘自动使它成为中心
https://jsfiddle.net/carinlynchin/uz0L5oow/10/
<div id="box1">
<img src="http://i44.tinypic.com/2j4akqb.jpg"/>
<div id="box2">box</div>
</div>
CSS:
#box1{
position:relative;
display:inline-block;
height: 200px;
}
img {
height: 100%;
}
#box2{
width:50px;
background-color: yellow;
position: absolute;
bottom:0;left:0; right:0;
margin:auto;
}
答案 1 :(得分:0)
因为box1是外框,所以你可以添加text-align
属性,以便#box2继承它。你的图像也比200px大;你可以改变239px的宽度;
jsfiddle
#box1{
position:relative;
display:inline-block;
width: 239px;
height: 200px;
text-align:center;
}
#box2{
background-color: yellow;
}
或者您可以将图像的宽度设置为200px
#box1{
position:relative;
display:inline-block;
height: 200px;
text-align:center;
}
#box1 img{
width:200px
}
#box2{
background-color: yellow;
}
答案 2 :(得分:0)
试试这个
<强> HTML 强>
<div id="box1">
<img src="http://i44.tinypic.com/2j4akqb.jpg"/>
<div id="box2">box</div>
</div>
<强> CSS 强>
#box1{
position:relative;
display:inline-block;
width: auto;
height: 200px;
background-color:#fff;
}
#box2{
width:50px;
text-align:center;
position:relative;
bottom:0%;
float:bottom;
margin: 0 auto;
background-color: yellow;
}
答案 3 :(得分:0)
这是一个适合你的解决方案吗?
#box1 {
position:relative;
display:table;
width: 200px;
height: 200px;
}
img {
position: absolute;
z-index: -2;
width: 100%;
}
#box2 {
width:50px;
margin: 0 auto;
left: 0%;
right: 0%;
bottom: 0%;
background-color: yellow;
z-index: 100;
position:absolute;
}