1. 正常布局流(Normal flow)
正常布局流是浏览器默认的HTML布局方式。
.wrapper{
}
.box1{
background:lightblue;
width:200px;
}
.box2{
background:pink;
width:200px;
}
<div class="wrapper">
<div class="box1">
The first blabla...
</div>
<div class="box2">
The second blabla...
</div>
</div>
这段HTML代码显示出来如下
HTML默认是水平书写模式,像上述两个div元素垂直排布的元素是块元素。块级元素占据其父元素的整个水平空间,垂直空间等于其内容高度。所以粉色块没有排布在蓝色块的旁边,而是在蓝色块的下面。
但是也有些元素是行内排布的,如<button>
<div>
<button>
save
</button>
<button>
delete
</button>
</div>
这种元素叫行内元素。
更多行内元素:https://developer.mozilla.org/zh-CN/docs/Web/HTML/Inline_elements
那如果我们想让蓝色块和粉色块也像button这样排布呢?我们可以使用display
属性。加上display:inline-block
,将它视为行内的一块。
.box2{
background:pink;
width:200px;
display:inline-block;
}
还可以使用弹性盒子布局(FlexBox), 在它们的父元素上加上display:flex
.wrapper{
display:flex;
}
2. 弹性盒子布局
在聊弹性盒子之前,先说说盒模型。在css中,所有元素都被一个个盒子包围着,这些盒子有内边距,边框和外边距。
弹性盒子布局很适合多布局任务。flex布局中,沿着flex元素放置的方向是主轴(main axis),垂直方向就是交叉轴(cross axis),设置display:flex
是flex容器,内部的弹性盒子元素称为flex项。
弹性盒子的换行
.wrapper{
display: flex;
width:400px;
}
<div class="wrapper">
<div class="box1">
The first blabla...
</div>
<div class="box2">
The second blabla...
</div>
<div class="box1">
The Third blabla...
</div>
</div>
.wrapper{
display: flex;
width:400px;
flex-wrap:wrap;
}
水平和垂直对齐
.wrapper{
display: flex;
width:500px;
height:50px;
align-items:center;
justify-content:space-around;
background:gray;
}
align-items
控制flex项在交叉轴的位置。默认值是stretch
,会使所有flex项沿交叉轴方向拉伸去填充父容器。center
会使这些项保持原有高度,但是会在交叉轴居中。justify-content
控制flex项在主轴上的位置。
3. 浮动
浮动的常见应用场景是在文本内浮动图像,但也适用于多列布局。
.wrapper{
background:gray;
width:400px;
}
.box{
float:left;
border-radius: 5px;
background:lightblue;
width:200px;
}
<div class="wrapper">
<div class="box">
image there is a picture
</div>
<p>
Long long ago, there is a king and queue...
</p>
</div>
在这个例子中,浮动元素会脱离正常的文档布局流,并吸附到父元素的左边。
清除浮动
让其他元素不受浮动影响,添加:
.cleared{
clear: left;
}
4.定位
静态定位
每个元素获取的默认值
相对定位
.wrapper{
background:gray;
width:400px;
}
.box1{
background:pink;
}
.box2{
position:relative;
left:20px;
top:5px;
background:skyblue;
}
<div class="wrapper">
<div class="box1">
Long long ago, there is a king and queue...
</div>
<div class="box2">
This is an another story.
</div>
</div>
绝对定位
绝对定位将元素固定在相对其位置最近的祖先。
position:absolute;
固定定位
固定定位固定元素相对于浏览器本身。
position: fixed;
</div>
</div>
绝对定位
绝对定位将元素固定在相对其位置最近的祖先。
position:absolute;
固定定位
固定定位固定元素相对于浏览器本身。
position: fixed;