[英]Div with background image and centered content
I need to make a div with background image of unknown size. 我需要使用未知大小的背景图像制作div。 Inside this div I need some content in the middle.
在这个div中,我需要在中间添加一些内容。
The problem is that I don't know the background image size. 问题是我不知道背景图像的大小。
I've found 2 solutions but I can't get it work together. 我找到了2个解决方案,但无法一起使用。 First, how to automatically adjust div width/height ad its background:
首先,如何自动调整其背景的div宽度/高度:
<div style="background:url(...); background-size: contain;">
<img src="the_same_url" style="visilibity: hidden;">
</div>
Second how to vertically align How to vertically align an image inside div 第二如何垂直对齐如何在div中垂直对齐图像
And also the content should be wrapped in wrapper (width: 960px; margin: 0 auto); 并且内容也应该用包装器包装(宽度:960px;边距:0自动); I cannot get it work together at all =\\
我根本无法一起工作= \\
So basically this thing is needed in order to create a block with some big background which will take 100% width of site and in the center there will be some content. 因此,基本上,需要用到此东西才能创建具有较大背景的块,该块将占据网站的100%宽度,并且在中心会有一些内容。 But the size of this block will depend on background image
但是此块的大小将取决于背景图片
Also I can use jQuery but I can't figure out how 我也可以使用jQuery但我不知道如何
You can do this with position:absolute;
您可以使用
position:absolute;
and display:table
/ display:table-cell;
并
display:table
/ display:table-cell;
. 。
HTML: HTML:
<div class="wrapper">
<img src="YOUR_IMAGE" />
<div class="content">
<div>
<div>
blahblab
</div>
</div>
</div>
</div>
CSS: CSS:
.wrapper {
width:960px;
margin:0 auto;
position:relative;
}
.wrapper > img {
width:100%;
height:auto;
}
.content {
top:0;
position:absolute;
width:100%;
height:100%;
}
.content > div {
display:table;
width:100%;
height:100%;
}
.content > div > div {
display:table-cell;
vertical-align:middle;
text-align:center;
}
Not sure if I understood your situation completely but would this work? 不知道我是否能完全理解您的情况,但是可以吗?
HTML: HTML:
<div id="wrapper">
<div id="background">
<img src="http://lorempixel.com/400/200/sports/">
</div>
</div>
CSS: CSS:
#wrapper {
margin: 0 auto;
width: 960px;
}
#background {
background: #ddd url('http://lorempixel.com/400/200/sports/') no-repeat;
background-size: cover;
background-position: center;
display: block;
text-align: center;
width: 100%;
height: auto;
}
#background img {
display: inline-block;
}
Here's the pen: http://codepen.io/andyngo/pen/seanA 这是笔: http : //codepen.io/andyngo/pen/seanA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.