在div的中间放置div,在bg中放置100%的图像

时间:2014-08-03 20:00:27

标签: html css

我想要一个包含适合100%

的图像的div

另一个按钮,将设置在中间,垂直和水平图像的中间和顶部。

奇怪的是,按钮总是在图像后面......

jsfiddle:http://jsfiddle.net/78xdJ/

HTML:

<div id="holder">
    <img src="http://mannerofspeaking.files.wordpress.com/2009/05/black1.gif" />
    <input type="button" value="aaaa" />
</div>

CSS:

#holder{
    position: relative;
}
#holder img{
    position: absolute;
    width: 100%;
}
#holder input{
    display: block;
    margin: auto;
}

4 个答案:

答案 0 :(得分:2)

完全适合img作为背景:

html { 
  background: url(images/bg.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

答案 1 :(得分:1)

试试这个:http://jsfiddle.net/mouhammed/78xdJ/4/

HTML:

<div id="holder">
    <img src="http://mannerofspeaking.files.wordpress.com/2009/05/black1.gif" />
    <input type="button" value="aaaa" />
</div>

CSS:

#holder{
    position: relative;
}

#holder img{
    width: 100%;
    position: relative;
    z-index:1;
}

#holder input{
    position:absolute;
    top:50%;
    left:50%;
    display: block;
    margin-left:-44px; /* negative margin with the width of button*/
    margin-top:-21px; /* negative margin with the height of button*/
    z-index:100;

}

答案 2 :(得分:1)

我已经更新了@ mouhammed的回答,无论如何将按钮放在中心。

http://jsfiddle.net/9FxeC/1/

基本上,你使用

 transform: translateX(-50%) translateY(-50%);

将按钮元素向上/向左拉动其宽度/高度的一半。

这应该适用于所有现代浏览器并返回ie9。

答案 3 :(得分:0)

我找到了答案,我将图像放在绝对位置,并为按钮添加div容器,它也是绝对的。

<style>
#holder{
position: relative;
}
#holder img{
position: absolute;
width: 100%;
top: 0;
left: 0;
}
#holder div{
position: absolute;
width: 100%;
top: 0;
left: 0;
text-align: center;
}
</style>

<div id="holder">
    <img src="http://mannerofspeaking.files.wordpress.com/2009/05/black1.gif" />
    <div>
        <input type="button" value="aaaa" />
    </div>
</div>