2016-03-05 45 views
0

我试图创建一个响应菜单,其中的按钮可以在窗口宽度低于800px的情况下移动位置。我已经完成了这个,但现在菜单的背景颜色随着按钮的位置而变化。我相信我已经将问题缩小到了浮动的使用范围,但是如果我没有将.section课程中的项目浮动到左侧,那么这些按钮将不再正确地更改位置。为什么#nav不会继承正确的背景色?如果漂浮是原因,我怎么能避免这个问题?下面是HTML:当窗口缩小时,div的背景颜色不会粘住

<div id="nav" class="clearfix"> 
    <div id="left" class="section"> 
    <div class="button vanish">TOC</div> 
    </div> 
    <div id="center" class="section"> 
    <div class="button">Home</div> 
    <div class="button">Contact</div> 
    <div class="button">About</div> 
    </div> 
    <div id="right" class="section"> 
    <div class="button vanish">Search</div> 
    </div>  
</div> 

这里是CSS:

@CHARSET "ISO-8859-1"; 
.clearfix { 
    display: block; 
    clear: both; 
} 
#container{ 
    margin: 0 auto; 
    max-width: 1200px; 
    font-family: Verdana, Sans-Serif; 
    font-size:15px; 
    background-color:#eee; 
} 
#header { 
    width: 94%; 
    padding: 3%; 
    background-color: #FF5722; 
    font-family: Serif; 
} 
#nav { 
    width: 97%; 
    background-color: #E64A19; 
    padding: 0 1.5% 0 1.5%; 
} 
.button{ 
    display: inline-block; 
    padding: 15px 1.5% 15px 1.5% ; 
} 
.button:hover { 
    color: #fff; 
    background-color:#000000; 
    text-decoration: none; 
} 
.vanish{ 
    display:none; 
} 
@media all and (max-width : 800px) and (min-width: 331px) { 
    #header { 
     text-align: center; 
    } 
    #content { 
     width: 94%; 
     padding: 3%; 
    } 
    .sidebar { 
     display: none; 
    } 
    .vanish{ 
     display:inline-block; 
    } 
    .section{ 
     display:inline-block; 
     float:left; 
    } 
    #left{ 
     width:20%; 
     text-align:left; 
    } 
    #right{ 
     width:20%; 
     text-align:right; 
    } 
    #center{ 
     width:60%; 
     text-align:center; 
    } 
} 

下面是上述代码的工作版本的链接:http://foothillertech.com/student/webdesign/2015/2nd/g_lebon0819/index/indexTestBenrud.php

回答

1

通过float的实现,各个元素移动到其位置,其余元素向上移动,以克服这类问题。 使用
overflow: auto;

在你的情况下使用它#nav。

+0

太棒了!这就像一个魅力。谢谢! –

0

添加一类clearfix到元素#nav

.clearfix::after { 
    display: block; 
    clear: both; 
} 

问题是由于原因,当th ere是一个带有浮动子元素的元素,那么它可能不会将它们包裹起来,因此会留下零(0)高度,因此样式会应用到父元素上,但是它的高度为0。

0

使用CSS

#nav { 
    overflow: auto; 
    background-color: #e64a19; 
    padding: 0 1.5%; 
    width: 97%; 
} 

,而不是

#nav { 
    background-color: #e64a19; 
    padding: 0 1.5%; 
    width: 97%; 
} 

编辑:哎呀!我没有注意到,同样的答案已经被@Aman

感觉为难给出... ;-)

0

试试这个代码:

就在#nav CSS添加fload:left

#nav { 
    float:left; 
    width: 97%; 
    background-color: #E64A19; 
    padding: 0 1.5% 0 1.5%; 
}