线上编辑器:JS Bin
简单用了3种方法(①position:absolute,②float,③flex),以及遇到的“脱离文档流”问题。
目录
脱离文档流
使用第一个方法的时候,遇到了元素脱离文档流的问题:
WHAT: 什么是脱离文档流?
元素脱离文档流之后,将不再在文档流中占据空间,而是处于浮动状态(可以理解为漂浮在文档流的上方)。
当一个元素脱离文档流后,依然在文档流中的其他元素将忽略该元素并填补其原先的空间。WHEN: 什么情况会脱离文档流?
- float浮动元素
- position:absolute/fixed/relative
HOW: 如何恢复文档流?
- float:对父级元素可以使用overflow:hidden
- 后面加一个空的元素,style=‘clear:both’
from《脱离文档流和恢复文档流的方法》
解决方法:
后面加一个空的元素,style=‘clear:both’
<br style="clear:both"/>
代码
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div style="height:30px;">三栏设计</div>
<div class="absolute3" style="background-color:red">
<div style="left:20px;">1</div>
<div style="left:20%">2 absolute方法,用clear:both清除浮动</div>
<div style="right:20px">3</div>
<br style="clear:both"/>
</div>
<div class="float3" style="background-color:yellow">
<div style="float:left">1</div>
<div style="float:right">2</div>
<div style="">3 关键</div>
</div>
<div class="flex" style="background-color:green">
<div style="">1</div>
<div style="flex-grow:1">2 按比例分配</div>
<div style="flex-grow:2">3</div>
</div>
</body>
</html>
css
div{border:1px solid black; margin:10px}
.absolute3 div{
position:absolute;top:42px;
}
.flex{
display:flex
}