水平垂直布局案例总结

水平垂直布局在前端开发中是经常使用到,在水平垂直布局中主要有两种情况,一种是知道元素的宽和高,一种是不知道宽高。

1. 已知宽高的元素进行水平垂直布局方案

方案一:
给父元素设置为相对定位,子元素设置绝对定位,且top,bottom,left和right为0,margin为auto

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<div id="fatherDom">
<div id="sonDom"></div>
</div>

<style>
#fatherDom{
width: 200px;
height: 200px;
position: relative;
}
#sonDom{
width: 100px;
height: 100px;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
</style>

方案二:
设置父元素为相对定位,子元素设置为绝对定位,且left和top为50%,margin-left为元素宽度的一半(负值),margin-top为元素高度的一半(负值)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<div id="fatherDom">
<div id="sonDom"></div>
</div>

<style>
#fatherDom{
width: 200px;
height: 200px;
position: relative;
}
#sonDom{
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
</style>

方案三:
给父元素设置display为flex,justify-content为center,align-items 为center。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div id="fatherDom">
<div id="sonDom"></div>
</div>

<style>
#fatherDom{
width: 200px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
}
#sonDom{
width: 100px;
height: 100px;
}
</style>

方案四:
使用calc计算属性, 父元素设置相对定位,子元素设置为绝对定位,left和top使用calc方法用50%减去宽高的一半。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<div id="fatherDom">
<div id="sonDom"></div>
</div>

<style>
#fatherDom{
width: 200px;
height: 200px;
position: relative;
}
#sonDom{
width: 100px;
height: 100px;
position: absolute;
left: calc(50% - 50px);
top: calc(50% - 50px);
}
</style>

2. 未知宽高的元素进行水平垂直布局方案

方案一:使用定位属性
给父元素设置为相对定位,子元素设置为绝对定位,且left和top为50%,transform设置为translateX和translateY为-50%;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div id="fatherDom">
<div id="sonDom">test dom</div>
</div>

<style>
#fatherDom{
width: 200px;
height: 200px;
position: relative;
}
#sonDom{
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
}
</style>

方案二:
给父元素设置display为flex,justify-content为center,align-items 为center。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div id="fatherDom">
<div id="sonDom"></div>
</div>

<style>
#fatherDom{
width: 200px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
}
#sonDom{
width: 100px;
height: 100px;
}
</style>

方案三:
给父元素设置display为table-cell, text-align为center,vertical-align为middle

1
2
3
4
5
6
7
8
9
10
11
12
13
<div id="fatherDom">
<div id="sonDom"></div>
</div>

<style>
#fatherDom{
width: 200px;
height: 200px;
display: table-cell;
text-align: center;
vertical-align: middle;
}
</style>
baishiwen wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!