如题,如何垂直居中一个元素,这里分为两种情况:要居中的元素已知大小、要居中的元素width, height未知。

1、要居中的元素已知大小

示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
#parent{
width:600px;
height:600px;
background:#ddd;
position:relative;
}
#son{
width: 300px;
height: 300px;
background-color:lightgreen;
position: absolute;
top: 50%;
left: 50%;
margin-top:-150px; /*二分之一的width和height,把元素往回拉*/
margin-left:-150px;
}
</style>
</head>
<body>
<div ></div>
</div>
</body>
</html>

2、要居中的元素width, height未知

示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
#parent{
width:600px;
height:600px;
background:#ddd;
position:relative;
}
#son{
max-width:40%;
max-height:50%;
background-color:green;
margin:auto;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
</style>
</head>
<body>
<div >
<p>高度,宽度未知的div元素</p>
<p>测试文本:Lorem ipsum dolor sit amet, consectetur adipisicing elit. </p>
</div>
</div>
</body>
</html>

这是我目前的做法,不足之处还望大家指出。

相关文章:

  • 2021-08-05
  • 2022-01-23
  • 2022-12-23
  • 2022-01-08
  • 2021-08-29
  • 2021-09-24
  • 2021-10-05
猜你喜欢
  • 2022-02-12
  • 2022-12-23
  • 2022-12-23
  • 2021-08-13
  • 2022-12-23
  • 2021-08-03
  • 2022-12-23
相关资源
相似解决方案