DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>CSS水平垂直居中实现方式--定位实现title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.p{
/*父元素为除了static以外的定位方式*/
position: relative;
/*position: absolute;*/
/*position: fixed;*/
width: 500px;
height: 500px;
border: 1px solid red;
}
.c{
/*子元素为绝对定位*/
position: absolute;
width: 200px;
height: 200px;
/*top、bottom、left和right 均设置为0*/
top: 0;
bottom: 0;
left: 0;
right: 0;
/*margin设置为auto*/
margin:auto;
border: 1px solid green;
}
style>
head>
<body>
<div class="p">
<div class="c">
子元素
div>
div>
body>
html>
DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>CSS水平垂直居中实现方式--定位实现title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.p{
width: 500px;
height: 500px;
border: 1px solid red;
display: table-cell;
/*vertical-align: middle; 实现垂直居中*/
vertical-align: middle;
}
.c{
width: 200px;
height: 200px;
border: 1px solid green;
/*margin: 0 auto; 实现水平居中*/
margin: 0 auto;
}
style>
head>
<body>
<div class="p">
<div class="c">
子元素
div>
div>
body>
html>
DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>CSS水平垂直居中实现方式--定位实现title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.p {
width: 500px;
height: 500px;
border: 1px solid red;
/*flex 布局*/
display: flex;
/*实现垂直居中*/
align-items: center;
/*实现水平居中*/
justify-content: center;
}
.c {
width: 200px;
height: 200px;
border: 1px solid green;
}
style>
head>
<body>
<div class="p">
<div class="c">
子元素
div>
div>
body>
html>
DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>CSS水平垂直居中实现方式--定位实现title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.p {
width: 500px;
height: 500px;
border: 1px solid red;
}
.c {
width: 200px;
height: 200px;
border: 1px solid green;
/*relative 定位*/
position: relative;
/*top和left偏移各为50%*/
top: 50%;
left: 50%;
/*translate(-50%,-50%) 偏移自身的宽和高的-50%*/
transform: translate(-50%, -50%);
}
style>
head>
<body>
<div class="p">
<div class="c">
子元素
div>
div>
body>
html>