元素水平垂直居中的方式
阿新 • • 發佈:2021-01-02
元素水平垂直居中的方式
HTML:
<body>
<div class="father">
<div class="son"></div>
</div>
<div class="oneline">單行文字居中</div>
</body>
CSS: .father { width: 600px; height: 600px; border: 1px solid #000000; position: relative; } .son { width: 100px; height: 100px; border: 1px solid #000000; background-color: #007ACC; }
1、第一種方法
.father {
display: flex;
justify-content: center;
align-items: center;
}
2、第二種方法
.father {
display: flex;
}
.son {
margin: auto;
}
3、第三種方法
.father {
display: flex;
}
.son {
align-self: center;
margin: auto;
}
4、第四種方法
.father { display: grid; } .son { /* 水平居中 */ justify-self: center; /* 垂直居中 */ align-self: center; }
5、第五種方法
.son {
margin: calc(50% - 50px) auto 0 auto;
}
6、第六種方法
.son {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
7、第七種方法
.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
8、第八種方式
.father { display: table-cell; vertical-align: middle; text-align: center; } .son { display: inline-block; }
9、第九種方式:單行文字框水平垂直居中
.oneline {
margin-top: 50px;
width: 600px;
height: 100px;
background: pink;
font-size: 25px;
text-align: center;
line-height: 100px;
}