浮动div时为什么会丢失CSS?

时间:2015-01-04 16:03:10

标签: html css

所以我试图创建一个响应式布局。一切都很好,直到我向左浮动一个div。然后我输了:

HTML

<body>
    <div class="wrapper">
    <h1>Site Title</h1>
    <nav>
        <a href="#">Home</a>
        <a href="#">Home</a>
        <a href="#">Home</a>
        <a href="#">Home</a>
        <a href="#">Home</a>
        <a href="#">Home</a>
    </nav>

    <h2>hello world</h2>
    </div>

</body>

CSS

.wrapper {
    margin: 10px auto;
    width: 90%;
    max-width: 980px;
    background-color: yellow;
    overflow: auto;
}

nav {
    background-color: #222;
    padding: 0;
    margin: 10px 0;
}


nav a { color: #F9F9F9; display: block; float:left;  padding: 10px;  }
nav a:visited { color: #f9f9f9; }
nav a:hover { text-decoration: none; background: #27B3CF; }
nav a:active { position: relative; top: 0; }

工作,但我想把它漂浮 http://jsfiddle.net/rktjam2k/4/

当导航a向左浮动时出现问题: http://jsfiddle.net/rktjam2k/3/

2 个答案:

答案 0 :(得分:4)

你必须清除浮子。

例如,添加

nav {
    overflow: hidden;
}

.wrapper {
  margin: 10px auto;
  width: 90%;
  max-width: 980px;
  background-color: yellow;
  overflow: auto;
}
nav {
  background-color: #222;
  padding: 0;
  margin: 10px 0;
  overflow: hidden;
}
nav a {
  color: #F9F9F9;
  display: block;
  float: left;
  padding: 10px;
}
nav a:visited {
  color: #f9f9f9;
}
nav a:hover {
  text-decoration: none;
  background: #27B3CF;
}
nav a:active {
  position: relative;
  top: 0;
}
a {
  outline: 0;
  text-decoration: none;
}
h1 {
  font-family: 'Droid Serif', serif;
  line-height: 75px;
  padding: 10px;
  font-size: 90px;
}
<div class="wrapper">
  <h1>Site Title</h1>
  <nav>
    <a href="#">Home</a>
    <a href="#">Home</a>
    <a href="#">Home</a>
    <a href="#">Home</a>
    <a href="#">Home</a>
    <a href="#">Home</a>
  </nav>
  <h2>hello world</h2>
</div>

或者

nav:after {
  content: '';
  display: block;
  clear: both;
}

.wrapper {
  margin: 10px auto;
  width: 90%;
  max-width: 980px;
  background-color: yellow;
  overflow: auto;
}
nav {
  background-color: #222;
  padding: 0;
  margin: 10px 0;
}
nav:after {
  content: '';
  display: block;
  clear: both;
}
nav a {
  color: #F9F9F9;
  display: block;
  float: left;
  padding: 10px;
}
nav a:visited {
  color: #f9f9f9;
}
nav a:hover {
  text-decoration: none;
  background: #27B3CF;
}
nav a:active {
  position: relative;
  top: 0;
}
a {
  outline: 0;
  text-decoration: none;
}
h1 {
  font-family: 'Droid Serif', serif;
  line-height: 75px;
  padding: 10px;
  font-size: 90px;
}
<div class="wrapper">
  <h1>Site Title</h1>
  <nav>
    <a href="#">Home</a>
    <a href="#">Home</a>
    <a href="#">Home</a>
    <a href="#">Home</a>
    <a href="#">Home</a>
    <a href="#">Home</a>
  </nav>
  <h2>hello world</h2>
</div>

答案 1 :(得分:0)

因为你不使用&lt;在CSS中!这应该使它正常工作

nav < a { color: #F9F9F9; display: block; float:left;  padding: 10px;  }
nav < a:visited { color: #f9f9f9; }