CSS浮动

CSS浮动

1、什么是浮动:

浮动的框可以向左或向右移动,浮动元素之后的元素将围绕它,直到它的外边缘碰到包含框另一个浮动框的边框为止。

如果包含框太窄,无法容纳水平排列的浮动元素,那么其它浮动块向下移动,直到有足够的空间。

如果浮动元素的高度不同,那么当它们向下移动时可能被其它浮动元素“卡住”。

2、用途:

多用于图像,使文本围绕在图像周围;有时用于布局。float 属性定义元素在哪个方向浮动。(用浮动布局IE6下可能会有问题。

eg:不用表格创建导航页

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>菜鸟教程(runoob.com)</title> 
<style>
* {
    box-sizing: border-box;
}
body {
    margin: 0;
}
.header {
    background-color: #2196F3;
    color: white;
    text-align: center;
    padding: 15px;
}
.footer {
    background-color: #444;
    color: white;
    padding: 15px;
}
.topmenu {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #777;
}
.topmenu li {
    float: left;
}
.topmenu li a {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 16px;
    text-decoration: none;
}
.topmenu li a:hover {
    background-color: #222;
}
.topmenu li a.active {
    color: white;
    background-color: #4CAF50;
}
.column {
    float: left;
    padding: 15px;
}
.clearfix::after {
    content: "";
    clear: both;
    display: table;
}
.sidemenu {
    width: 25%;
}
.content {
    width: 75%;
}
.sidemenu ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}
.sidemenu li a {
    margin-bottom: 4px;
    display: block;
    padding: 8px;
    background-color: #eee;
    text-decoration: none;
    color: #666;
}
.sidemenu li a:hover {
    background-color: #555;
    color: white;
}
.sidemenu li a.active {
    background-color: #008CBA;
    color: white;
}
</style>
</head>
<body>

<ul class="topmenu">
  <li><a href="#home" class="active">主页</a></li>
  <li><a href="#news">新闻</a></li>
  <li><a href="#contact">联系我们</a></li>
  <li><a href="#about">关于我们</a></li>
</ul>

<div class="clearfix">
  <div class="column sidemenu">
    <ul>
      <li><a href="#flight">The Flight</a></li>
      <li><a href="#city" class="active">The City</a></li>
      <li><a href="#island">The Island</a></li>
      <li><a href="#food">The Food</a></li>
      <li><a href="#people">The People</a></li>
      <li><a href="#history">The History</a></li>
      <li><a href="#oceans">The Oceans</a></li>
    </ul>
  </div>

  <div class="column content">
    <div class="header">
      <h1>The City</h1>
    </div>
    <h1>Chania</h1>
    <p>Chania is the capital of the Chania region on the island of Crete. The city can be divided in two parts, the old town and the modern city.</p>
    <p>You will learn more about responsive web pages in a later chapter.</p>
  </div>
</div>

<div class="footer">
  <p>底部文本</p>
</div>

</body>
</html>

3、浮动会导致的问题——父元素高度坍塌 

3.1什么是父级元素高度塌陷

 想要的效果:

 加浮动后,父级元素高度塌陷:

 

 怎样解决父级元素高度塌陷,请看后篇总结。

 

posted on 2018-09-20 09:58  念稚朗朗  阅读(44)  评论(0)    收藏  举报

导航