【css】弹性盒模型

时间:2023-03-09 18:35:56
【css】弹性盒模型

弹性盒模型flexBox

弹性盒模型是c3的一种新的布局模式

它是指一种当页面需要适应不同屏幕大小以及设备类型时,确保元素有恰当行为的布局方式。

引入弹性盒模型布局的目的是提供一种更有效的方法来对一个容器中的子元素进行排列、对齐和分配空白空间

兼容性

IE11

弹性盒模型内容

弹性盒模型由弹性容器(flex container)和弹性子  元素(flex item)组成

将父容器设置display:flex转换为弹性容器

介绍几个常用方法:

flex-direction: 

row:横向从左到右排列,默认

row-reverse:横向从右到左排列(最后一项在最前面)

column:纵向排列

column-reverse:反转纵向排列(最后一项排在最上面)

justify-content:

  flex-start:起始点对齐(左对齐)

  flex-end:终止点对齐(右对齐)

  center:居中对齐

  space-around:四周环绕

  space-between:两端对齐

让盒子水平垂直居中的方法:

1 使用弹性盒模型 display:flex + justify-content:center + align-items:center

    <style>
.box{
width: 400px;
height: 300px;
display: flex; 让盒子变成弹性盒模型
justify-content: center; 居中
align-items: center; 居中
background-color: pink;
} .child{
width: 150px;
height: 150px;
background-color: skyblue;
} </style>
</head>
<body> <div class="box">
<div class="child"></div>
</div>

2 使用position:absolute + transform:translate

     .box{
width: 400px;
height: 300px;
position: relative;
background-color: pink;
} .child{
width: 150px;
height: 150px;
background-color: skyblue;
position: absolute;
top: 50%;
left: 50%;
transform:translate(-50%,-50%)
} </style>
</head>
<body> <div class="box">
<div class="child"></div>
</div>