Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

清除浮动 #50

Open
TieMuZhen opened this issue Nov 28, 2021 · 0 comments
Open

清除浮动 #50

TieMuZhen opened this issue Nov 28, 2021 · 0 comments
Labels

Comments

@TieMuZhen
Copy link
Owner

浮动的定义

使元素脱离文档流,按照指定方向发生移动,遇到父级边界或者相邻的浮动元素停下来

浮动的用途

可设置文字环绕或使元素宽度由内容填充(类似Inline-block)。使用浮动需要注意的是如果浮动的元素高度比父级容器还高,那么需要设置父级容器的overflow属性为auto,使其自动撑满

浮动用法

分析HTML结构:

<div class="box">
  <div class="div1">1</div>
  <div class="div2">2</div>
  <div class="div3">3</div>
</div>

分析CSS代码样式:

.box {
  border: 1px solid #ccc;
  background: #fc9;
  color: #fff;
  margin: 50px auto;
  padding: 50px;
}
.div1 {
  width: 100px;
  height: 100px;
  background: darkblue;
  float: left;
}
.div2 {
  width: 100px;
  height: 100px;
  background: darkgoldenrod;
  float: left;
}
.div3 {
  width: 100px;
  height: 100px;
  background: darkgreen;
  float: left;
}

清除浮动三种方式

添加新元素,应用clear:both;

.clear {
  clear: both;
  height: 0;
  line-height: 0;
  font-size: 0
}
<div class="box">
  <div class="div1">1</div>
  <div class="div2">2</div>
  <div class="div3">3</div>
  <div class="clear"></div>
</div>

利用BFC,父级div定义overflow:auto;

.box {
  border: 1px solid #ccc;
  background: #fc9;
  color: #fff;
  margin: 50px auto;
  padding: 50px;
  overflow: auto; 
  zoom: 1; /*zoom: 1; 是在处理兼容性问题 */
}
<div class="box">
  <div class="div1">1</div>
  <div class="div2">2</div>
  <div class="div3">3</div>
</div>

在父级样式添加伪元素::after或者::before(推荐)

.box {
  border: 1px solid #ccc;
  background: #fc9;
  color: #fff;
  margin: 50px auto;
  padding: 50px;
}
.box::after{
  content: '';
  display: block;
  clear: both;
}
<div class="box">
  <div class="div1">1</div>
  <div class="div2">2</div>
  <div class="div3">3</div>
</div>

拓展: 在全局最前面将uldiv清楚浮动,这样后面的uldiv就不用清除浮动了。这是企业封装样式的思想,在全局最前面定义公共样式

ul::after,
div::after{
  content: '';
  display: block;
  clear: both;
}
...
...   其它样式代码
...
@TieMuZhen TieMuZhen added the CSS label Nov 28, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant