文章目录
0、body 内容
<body>
<div class="d1">
<div class="d2">
<span>222</span>
</div>
</div>
</body>
0、效果图
一、BFC & margin
已知父子宽高!!!给父元素 overflow: hidden;(BFC),父子 margin 就不会共用
BFC: 块格式化上下文(Block Formatting Context)
<style>
.d1 {
margin: 100px;
width: 300px;
height: 300px;
background-color: beige;
overflow: hidden;
}
.d2 {
width: 100px;
height: 100px;
margin: 100px;
background-color: blue;
/* 文本垂直和水平居中 */
line-height: 100px;
text-align: center;
}
</style>
二、position & translate
transform:变化
translate:转动,移动
<style>
.d1 {
margin: 100px;
width: 300px;
height: 300px;
background-color: beige;
position: relative;
}
.d2 {
width: 100px;
height: 100px;
top: 50%; /* 让盒子顶部距离父顶部一半 */
left: 50%; /* 让盒子左部距离父左部一半 */
transform: translate(-50%, -50%); /* 让盒子中心点落在中间 */
position: absolute;
background-color: blue;
}
</style>
三、display:flex(弹性布局)
flex属性
容器的属性
:第一个值为默认值
- flex-direction: row | row-reverse | column | column-reverse;
- flex-wrap: nowrap | wrap | wrap-reverse;
- flex-flow:
<flex-direction> <flex-wrap>
- justify-content: flex-start | flex-end | center | space-between | space-around;
:项目在交叉轴的对齐方式
:baseline:文字会在一条直线上
:stretch为默认值(项目高度==容器的高度,内容太多会溢出!直系子元素没有设置高度才有效)
:align-content:定义多根轴线的对齐方式(只有一行时不起作用)
- align-items: flex-start | flex-end | center | baseline | stretch;
- align-content: flex-start | flex-end | center | space-between | space-around | stretch;
项目的属性
order:
<number>
; / 排序(数值大向右走) default 0 /
flex-grow:<number>
; / 放大比例 default 0 /
flex-shrink:<number>
; / 缩小比例(只有当空间不足时有效) default 1 /
flex-basis:<length>
; / default auto (可以用px等)/
flex: 前三个的简写(推荐) / default 0 1 auto /
align-self: 单个项目的 align-items,默认auto,表示继承父元素的
<style>
.d1 {
margin: 100px;
width: 300px;
height: 300px;
background-color: beige;
display: flex;
align-items: center; /* 垂直居中(轴线在父元素垂直方向上的中间) */
justify-content: center; /* 水平居中(项目在轴线中间) */
}
.d2 {
width: 100px;
height: 100px;
background-color: blue;
/* 文本垂直和水平居中 */
line-height: 100px;
text-align: center;
}
</style>
四、display:table-cell
<style>
.d1 {
margin: 100px; /* margin无效,padding有效!!! */
width: 300px;
height: 300px;
background-color: beige;
/* 垂直居中 middle */
display: table-cell;
vertical-align: middle;
}
.d2 {
width: 100px;
height: 100px;
background-color: blue;
margin: auto; /* 水平居中 */
/* 文本垂直和水平居中 */
line-height: 100px;
text-align: center;
}
</style>
五、其他
1.如上(若不是行元素 display:inline): line-height (已知宽高)
2.父相对和子绝对定位 : top(和其他三个): 0; margin: auto;