CSS布局技巧 | 青训营

102 阅读2分钟

1.float 浮动.

浮动元素的顶部,在标准文档流的底部.

浮动会脱离文档流,当一个元素浮动之后,不会影响到块级元素的布局而只会影响内联元素(通常是文本)的排列,文档中的普通流就表现得如同浮动框不存在一样。

实操实践

<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<style>
		.box1{
			width: 200px;
			height: 200px;
			background-color: rgb(241, 0, 221);
			float: left;
		}
		.box2{
			width: 500px;
			height: 100px;
			background-color: rgb(240, 156, 0);
			/* float: left; */
		}
		.box3{
			width: 400px;
			height: 200px;
			background-color: rgb(24, 223, 123);
			float: left;
		}
		.box4{
			width: 300px;
			height: 400px;
			background-color: rgb(0, 132, 255);
			float: left;
		}
	</style>
</head>
<body>
	<div class="box1">div1</div>
	<div class="box2">div2</div>
	<div class="box3">div3</div>
	<div class="box4">div4</div>
</body>
</html>

2.position 定位

relative 相对定位:相对原来位置,便宜一定距离

absolute 绝对定位:相对position不为static的父元素,偏移一定距离

fixed 固定定位:相对浏览器定位

static 没有定位:

top 上 bottom 下 left 左 fight 右

实操实践

}

.left {position: absolute;width: 200px;height: 100%;background-color: red;
}

.main {margin: 0 100px 0 200px;height: 100%;background-color: green;
}

.right {position: absolute;top: 0;right: 0;width: 100px;height: 100%;background-color: blue;
}

3.flex布局

flex-direction 主轴方向

row 行排布 row-reverse 同一行反向排布 column 列排布 column-reverse 同一列反向排布

justify-content 主轴子元素排列

flex-start 从头部排列 flex-end 从尾部排列 center 居中排列 space-around 平分剩余 space-between 两边贴边,平分剩余

align-items 侧轴子元素排列方式

flex-start 从上到下 flex-end 从下到上 stretch 拉伸(子元素去掉高度) center 居中

flex-wrap 是否换行

wrap 换行 no-wrap 不换行

align-content 侧轴多行换行属性

flex-start 侧轴头部排列 flex-end 侧轴尾部排列 center 居中排列 space-around 恻轴平分空间 space-between 侧轴两端对齐

实操实践

            width: 100%;
            margin-bottom: 30px;
            border:2px solid red;
            box-sizing: border-box;
            display: flex;
        }
        .wrapper .left {
            width: 200px;
            height: 300px;
            background: #faa;
        }
        .wrapper .right {
            width: 200px;
            height: 500px;
            background: #afa;
        }
        .wrapper .content {
            flex: 1;
            height: 400px;
            background-color: #aaf;
        }

总结:通过今天的实践选题学习,我学习到了许多非常有用的CSS布局技巧,让我在今后的前端学习和项目开发中拥有更好的基础。