欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

让一个盒子在页面上既能水平居中又能垂直居中的方法

最编程 2024-02-13 08:16:38
...

snipaste20220429_221734.jpg

body内容区

<body>
<div class="parent">
   <div class="child">我是子元素</div>
</div>
</body>

方法一:利用定位(常用方法)

<style>
.parent {
width: 500px;
height: 500px;
border: 1px solid #000;
position: relative;      给父盒子设置相对定位
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
position: absolute;    给子盒子设置绝对定位
top: 50%; 
 子盒子距离距离父盒子上面50%
left: 50%;
 子盒子距离距离父盒子左边50%
margin-top: -50px;     
//然后在向相反方向移动自身盒子大小的一半即可实现水平垂直居中  
margin-left: -50px;
}
</style>

方法二:利用 margin:auto;

<style>
.parent {
width: 500px;
height: 500px;
border: 1px solid #000;
position: relative;   给父盒子设置相对定位
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
position: absolute;  子盒子绝对定位
margin: auto;  使子盒子水平居中然后四个方向的值全部设置为0   
top: 0;
left: 0;
right: 0;
bottom: 0;
}
</style>

方法三:利用 display:table-cell

<style>
.parent {
width: 500px;
height: 500px;
border: 1px solid #000;
display: table-cell;       设置为表格单元格(类似 <td> 和 <th>)
vertical-align: middle;    设置为垂直对齐,在表单元格中
这个属性会设置单元格框中的单元格内容的对齐方式
text-align: center; 子盒子设置为水平居中
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
display: inline-block;       转换为行内块元素
}
</style>

方法四:利用 display : flex; 设置垂直水平都居中

<style>
.parent {
width: 500px;
height: 500px;
border: 1px solid #000;
display: flex;              设为flex弹性布局
justify-content: center;    使子盒子水平居中
align-items: center;        使子盒子垂直居中
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
}
</style>

方法五:计算父盒子与子盒子的空间距离(这跟方法一是一个道理)

<style>
.parent {
width: 500px;
height: 500px;
border: 1px solid #000;
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
margin-top: 200px;
margin-left: 200px;
   设置子盒子距离上左方向200px在加上自身的100px就是水平垂直居中
}
</style>

方法六:利用 transform

<style>
.parent {
width: 500px;
height: 500px;
border: 1px solid #000;
position: relative;   父盒子设置相对定位
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
position: absolute;  子盒子设置绝对定位
top: 50%;      距离父盒子左上距离50%
left: 50%;
transform: translate(-50%, -50%); 使用平移属性,平移自身宽高反方向的一半
}
</style>

以上就是使盒子居中的6种方法