2015-01-05 39 views
0

我正在继续使用HTML和CSS进行练习。我正在尝试将图片放在页面的宽度上,并位于标题下方。出于某种原因,当我试图扩展它时,它将不起作用。我的猜测是,我还没有遇到过这样做的选择。标题图片不会覆盖页面宽度

CSS

#header { 

height: 80px; 
background-color: gray; 
margin-bottom: 60px; 


} 

.container { 

} 

.MainImage { 

background-image:url(computers.jpg); 
height: 400px; 
background-repeat: no-repeat; 
width: 100%; 

} 

.MainImage img { 

position: relative; 
background-size: cover; 

} 

HTML

<body> 

<div id = "header"> 
<div class = "nav"> 

    <!-- container-fluid gives full width container of whole viewport --> 

    <div class = "container-fluid"> 


    <ul id = "nav" class= "text-left"> 
     <li><a href = "#"><strong>Home</a></li> 
     <li><a href = "#">Technologies</a></li> 
     <li><a href = "#">Programs</a></li> 
     <li><a href = "#">Blog</strong></a></li> 
    </ul> 

    <ul id = "nav" class = "text-right"> 
     <li><a href = "#"><strong>Sign Up</a></li> 
     <li><a href = "#">Sign In</a></li> 
     <li><a href = "#">Contact</strong></a></li> 
    </ul> 

    </div><!-- end container-fluid--> 
</div><!--end nav--> 
</div> <!-- end header --> 



<div id = "Main"> 


    <div class = "MainImage"> 


    </div> 


</div><!--end Main--> 



</body> 

http://jsfiddle.net/xehu1tg0/

UPDATE:我的IE 10的图像错误

enter image description here

+0

尝试使用CSS第一中心图像'文本对齐:中心;'然后可以增加宽度为100%。我也看到你正在使用它作为背景图像,尝试为图像的CSS规则添加'background-size:cover;' – Lee

+0

使用'background-size:100%100%'-----> [Fiddle ](http://jsfiddle.net/xehu1tg0/3/)。 –

回答

2

您需要添加background-size: 100% auto;.MainImage类,像这样:只有

.MainImage { 
    background-image:url(http://www.onlineuniversities.com/wp-content/uploads/improving-tech-literacy.jpg); 
    height: 500px; 
    background-repeat: no-repeat; 
    background-size: 100% auto; 
    width: 100%; 
} 

heightwidth属性影响容器元素,不背景图像本身。

100% auto本质上意味着图像大小应该是其容器宽度的100%,并且高度应该随宽度自动缩放(在这里您会看到两个像这样的值,第一个值几乎总是与x轴相关,第二个与y轴有关。)

我希望有道理吗?

例子: http://jsfiddle.net/w1020vu1/

+0

这工作得很好,但我的IE 10不接受它,只有谷歌浏览器。 – narue1992

+0

你在IE 10中看到什么?我不知道为什么这不应该在IE 10中工作,因为它支持'background-size'属性(http:// caniuse。com /#search = background-size) – Sean

+0

您是否尝试过使用IE10检查代码?它是否显示开发人员工具中的'background-size'属性? – Sean

1

首先,由于您通过CSS的background-image属性而不是img属性为src属性分配图像,因此您的.MainImage img选择器不执行任何操作。

至于.MainImage,样式,heightwidth属性只影响容器元素,而不影响背景图像。要设置背景图片大小,使用这种风格:

.MainImage { 
    background-size: 100% auto; 
} 
+0

好的谢谢你的解释。我意识到谷歌接受这种格式,但我的IE 10没有。你能解释为什么吗? @ im1dermike – narue1992

+0

@AlyssaCooke:它在IE10中对我很好。请重新检查您的代码。 – im1dermike

0

除了提供的答案,我决定为我的IE浏览器的兼容性可能是一个问题。

在<头部>我inputed以下代码:

<meta http-equiv="X-UA-Compatible" content="IE=80" />