我有1400像素×400像素的图像,需要在我的div中修复为背景。 问题是我想让背景图像大小保持其比例并适合div。
这是我的代码,您可以查看我的代码(底部的链接)并帮我弄明白吗?
#pageheader{
background: black url(http://s21.postimg.org/ml0zsve7p/test_image.jpg) no-repeat center center fixed !important;
padding-top: 70px;
padding-bottom: 35px;
height: 400px;
max-width: 1400px;
overflow: hidden;
-webkit-background-size: 100% !important;
-moz-background-size: 100% !important;
-o-background-size: 100% !important;
background-size: 100% !important;
}
.container {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
}
#textwrap {
padding-top: 35px;
padding-bottom: 35px;
background: white;
}
#textwrap h4 {
color: #4c4d4e;
font-size:20px;
text-transform: capitalize;
font-family: "GothamBook";
}
#textwrap p {
color: #4c4d4e;
text-align: left;
}
答案 0 :(得分:2)
您需要background-size:cover;
选项,这会使您的图片展开以覆盖div,同时保持其比例。见here。这在IE9及更高版本中受支持。如果您也想支持IE8,可以使用this polyfill。
这是一个更新的jsFiddle。
编辑:我想我现在明白了这个问题。查看this fiddle。答案 1 :(得分:0)
检查http://www.w3.org/TR/css3-background/#the-background-size
您似乎想要background-size:contain
或background-size:cover
答案 2 :(得分:0)
我认为你的问题不是因为css,而是来自重定向到html页面的图片网址只知道每个浏览器和每台计算机的网址都不同,所以它不应该'是你的网址问题。 首先尝试检查您的图片网址,并为您的css
-webkit-background-size: 100% !important;
-moz-background-size: 100% !important;
-o-background-size: 100% !important;
background-size: 100% !important;
最好删除!important
,因为你没有另外的css可以更改id pageheader
的背景大小,如果你想写,它是可选的
background-size: 100%;
或
background-size: cover;
并删除背景中的fixed
<强>更新强>
尝试将此JSFiddle复制到您的HTML并尝试解决您的问题
答案 3 :(得分:0)
如果您真的希望图像保持纵横比,例如您提供的第二个链接...那么您就无法设置div的高度(400px)
也许您需要考虑使用实际的img标签,然后使用该元素的自然形状来给它的父母提供比率。
步骤1.不要使用bootstrap:
<header class="container global-header">
<div class="inner-w">
<div class="image-w">
<img src="http://placehold.it/1400x400" alt="" />
</div>
<div class="your-text"> <!-- position:absolute; on top -->
<p>Yo, this is some text... </p>
</div>
</div>
</header>
步骤2.制作您自己的简单基本样式并了解它们的工作原理 - 非常好。
/* global */
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
body {
margin: 0;
}
/* structural elements */
.container {
width: 100%;
float: left;
}
.container .inner-w {
position: relative;
width: 100%;
max-width: 1400px;
margin-right: auto;
margin-left: auto;
padding: 1rem;
}
/* basic responsive images */
.image-w img { /* (any image in a .image-w will fit the .image-w) */
display: block;
width: 100%;
height: auto;
}
/* header */
.global-header {
background-color: wheat;
}
.global-header .inner-w {
padding: 0;
}
.global-header .your-text {
position: absolute;
top: 0;
left: 0;
padding: 1rem;
}
/* main content */
.main-content {
background: lightblue;
}
.main-content .inner-w {
background: pink;
}
你可能应该根据窗口大小和显示类型使用javascript来提供不同的图像,这样你就不会无缘无故地给手机提供巨大的图像。 :)
http://codepen.io/sheriffderek/pen/zruIy
如果您不需要100%完全相同的比例,我将如何设置背景图像: