水平垂直居中多种实现方式

文章类型:CSS

发布者:hp

发布时间:2023-02-08

实现元素的水平垂直居中,有多种方式

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
.out-box{
width: 300px;
height:300px ;
background: gainsboro;

}
.in-box{
width: 50px;
height:50px ;
background: ghostwhite;

}
</style>
</head>
<body>
<div class="out-box">
<div class="in-box"></div>
</div>
</body>
</html>

方式一 :flex变异布局,直接给父元素使用flex或者grid,子元素margin 自动

              <style>
.out-box{
display: flex;
//display: grid;
}
.in-box{
margin: auto;
}
</style>

方式二:利用绝对定位,设置 left: 50% 和 top: 50% 现将子元素左上角移到父元素中心位置,然后再通过 translate 来调整子元素的中心点到父元素的中心,【不定宽高

<style>
.out-box{

position: relative;
}
.in-box{

position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>

方式三:利用绝对定位,子元素所有方向都为0 ,将margin 设置为auto ,由于宽高固定,对应方向实现平分,【盒子有宽高】

<style>
.out-box{

position: relative;
}
.in-box{

position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0px;
margin: auto;

}
</style>

方式四:利用绝对定位,设置 left: 50% 和 top: 50% 现将子元素左上角移到父元素中心位置,然后再通过 margin-left 和 margin-top 以子元素自己的一半宽高进行负值赋值,【定宽高】

<style>
.out-box{

position: relative;
}
.in-box{

position: absolute;
left: 50%;
top: 50%;

margin-left: -25px;
margin-top: -25px;

}
</style>

方式五:利用flex属性

<style>
.out-box{

display: flex;
justify-content: center;
align-items: center;
}
.in-box{
width: 50px;
height:50px ;
background: ghostwhite;


}
</style>

方式六:table-cell属性布局

<style>
.out-box{

display: table-cell;
text-align: center;
vertical-align: middle;
}
.in-box{
width: 50px;
height:50px ;
background: ghostwhite;
display: inline-block;
//margin: auto

}
</style>

方式七:writing-mode属性布局

<style>
.out-box{
width: 300px;
height:300px ;
background: gainsboro;
writing-mode: vertical-lr;
text-align: center;
}
.second-box{
width: 100%;
writing-mode: horizontal-tb;
display: inline-block;
text-align: center;
}
.in-box{
width: 50px;
height:50px ;
background: ghostwhite;
display: inline-block;
margin: auto;

}
</style>

<div class="out-box">
<div class="second-box">
<div class="in-box"></div>
</div>

</div>

一、内联元素居中布局

水平居中

行内元素可设置:text-align: center;

flex布局设置父元素:display: flex; justify-content: center;

垂直居中

单行文本父元素确认高度:height === line-height

多行文本父元素确认高度:disaply: table-cell; vertical-align: middle;

二、块级元素居中布局

水平居中

定宽: margin: 0 auto;

垂直居中

position: absolute设置left、top、margin-left、margin-to(定高);

position: fixed设置margin: auto(定高);

display: table-cell;

transform: translate(x, y);

flex(不定高,不定宽);

grid(不定高,不定宽),兼容性相对比较差;