抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

Mr.wang

Time flies and people come and go

html关于css的居中布局方式

HTML

盒子居中的方法:

1.宽度和高度已知的。

思路:
父元素相对定位
子元素绝对定位

子元素{

left: 50%;top: 50%;
margin-left: 减去子元素的宽度一半。
margin-top: 减去子元素的高度一半;

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<style type="text/css">
#box{
width: 400px;
height: 200px;
position: relative;
background: red; //方便观看
}
#box1{
width: 200px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px; //定位后偏移值超过子元素的宽度一半需减去
margin-top: -50px; //定位后偏移值超过子元素的高度一半需减去
background: green;
}
2.宽度和高度可以随意改变

思路:
父元素相对定位
子元素绝对定位

子元素{

left: 0;top: 0; bottom:0;right:0;

margin:auto;

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#box{
width: 800px;
height: 400px;
position: relative;
background: red;
}
#box1{
width: 100px;
height: 50px;
position: absolute;//四个方位定义盒子所在的位置 当所有为0&&margin:auto时,盒子居中
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
background: green;
}

3.flex布局
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.box{
width: 400px;
height: 200px;
background: #f99;
}
.box1{
width: 200px;
height: 100px;
background: green;
}
.center{
display: flex; //开启弹性盒子 主轴侧轴交叉得到居中
justify-content: center;//实现水平居中
align-items: center;//实现垂直居中
}
4.平移 定位+transform
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.parent_box{
width: 400px;
height: 200px;
background: red;
position: relative;
}
.child_box{
width: 200px;
height: 100px;
background: green;
position: absolute;//与第一个类似 但可以根据子元素的宽高自动居中
top: 50%;
left: 50%;
transform: translate( -50%,-50%);//平移相当于盒子margin(左,上)减半
}

评论