一、水平居中(即横向纵向都位于盒子中间)
1、子元素设置:margin: 0 auto; line-height等于height;
<style>
body{
}
.father{
width: 300px;
height: 300px;border: 1px solid #000;
margin: 0 auto;
display: flex;
}
.son{
width: 100px;height: 100px;
border: 1px solid #000;
background-color: pink;
align-self: center;
margin: 0 auto;
line-height: 100px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
2.利用绝对和相对定位(利用绝对相对定位有多种方法,以下只举例较为简便方法)
absolute + transform
<style>
body{
}
.father{
width: 300px;
height: 300px;border: 1px solid #000;
position: relative;
}
.son{
width: 100px;height: 100px;
border: 1px solid #000;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
absolute + margin: auto
<style>
body{
}
.father{
width: 300px;
height: 300px;border: 1px solid #000;
margin: 0 auto;
position: relative;
}
.son{
width: 100px;height: 100px;
border: 1px solid #000;
background-color: pink;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
三、利用flex布局
<style>
body{
}
.father{
width: 300px;
height: 300px;border: 1px solid #000;
display: flex;
justify-content: center;
align-items: center;
}
//或者父元素设置display: flex; 子元素设置margin: auto;
.son{
width: 100px;height: 100px;
border: 1px solid #000;
background-color: pink;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
需掌握至少三种居中方法:
即单操作父元素居中display: flex; justify-content: center;align-items: center; ,
单操作子元素居中margin: 0 auto;line-height: 100px;,
以及操作俩者居中
position: relative;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
附:
实现横向居中的简单方法:
元素设置 margin: 0 auto;
实现元素纵向居中简单方法:
父元素设置 display: flex; 子元素设置align-self: center;