2015-04-04 42 views
0

我想水平居中在另一个DIV中有一个图像的DIV中。我可以让它与父\子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

我想我应该澄清我的意思,DIV需要位于​​图像之上。请参阅编辑 – 2015-04-05 17:46:54

+0

这里有两个简单的方法来将div集中在div中,垂直,水平或两者(纯CSS):http://stackoverflow.com/a/31977476/3597276 – 2015-08-20 15:24:41

回答

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; 
} 

,或者你可以设置宽度为200像素的图像

jsfiddle

#box1{ 
    position:relative; 
    display:inline-block; 
    height: 200px; 
    text-align:center; 

} 

#box1 img{ 
width:200px 
} 


#box2{ 
    background-color: yellow; 
} 
0

Live Demo

试试这个

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; 
} 
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; 
} 

工作示例: https://jsfiddle.net/ba5z1zm3/2/

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; 
}