首页 前端

css-居中布局解决方案

发布于: 2020-06-09

指当前元素在父级元素容器中,水平方向是居中显示

方案一:inline-block + text-algin 属性配合使用

优缺点:

兼容性好

text-algin属性具有继承性,导致子元素的文本也是居中显示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#parent{
width: 100%;
height: 200px;
background: #ccc;
/*
* text-aglign属性值
* - left(左对齐)
* - center(居中)
* - right(右对齐)
* display属性值:
* - block 块级元素
* - inline 内联元素
* - inline-block 行内块级元素(块级+内联)
*/
text-align:center;
}
#child{
width: 200px;
height: 200px;
background: red;
display: inline-block;
}
/*在上面代码中child无论是块还是文本都会显示居中,如果想要文本左对齐,那么就需要*/
#child{
text-align:left;
}
</style>

<div id="parent">
<div id="child">我是谁</div>
</div>

方案二:table+margin 属性配合使用

优:只需要对子元素进行设置可以实现水平居中布局

缺:子元素脱离文档流,导致margin属性值无效

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<style>
#parent{
width: 100%;
height: 300px;
background:aquamarine;
}
#child{
width: 300px;
height: 300px;
background:red;
/**
* margin属性:外边距
* - 一个值: 上右下左
* - 两个值: 上下,左右
* - 三个值: 上,左右,下
* - 四个值: 上,右,左,下
*/
display:table;
margin: 0 auto;
}
</style>
<div id="parent">
<div id="child">我是谁</div>
</div>

方案三:absolute+ transform 属性配合使用

优缺点

优:父级元素是否脱离文档流,不影响子级元素水平居中

缺:transform属性css3中新增的属性,浏览器支持不友好

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<style>
#parent{
width: 100%;
height: 200px;
background: #ccc;
/*
* 开启定位
* absolute 绝对定位
* fixed 相对固定定位
* relative 相对定位
* */
position: relative;
}
#child{
width: 200px;
height: 200px;
background: red;
/*
* 当前元素设置绝对定位之后:
* 若父级没有开启定位,当前元素相当于页面定位
* 若父级开启定位的话,当前元素相当于当前父类进行定位
*
* */
position: absolute;
left: 50%;
/*
* 水平方向平移 (向左移动)
* 移动的大小是根据当前元素的宽度来决定
*/
transform: translateX(-50%);
}

</style>

<div id="parent">
<div id="child">我是谁</div>
</div>