css不定宽高水平垂直居中
1、新建一个html文件,在这个html文件上创建一个<div>,然后对这个<div>添加一个样式类,最后在这个<div>里再创建一个子元素并在这个元素中添加要垂直居中的内容。
代码:
<div class="paernt">
<div>
不宽高的水平垂直居中<br/>
不宽高的水平垂直居中<br/>
</div>
</div>
2、设置父元素样式。使用Flexbox弹性盒子让子元素自动水平垂直居中;使用justify-content设置子元素水平居中,使用align-items设置子元素垂直居中。
css代码:
<style type="text/css">
.parent{
height: 300px;
background-color: #96b97d;
justify-content: center;
align-items: center;
display: flex;
}
</style>

3、保存html文件后使用浏览器打开即可看到效果。如图

4、可以直接复制所有代码到新建的html文件上,粘贴保存后运行即可看到效果。
所有代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.parent{
height: 300px;
background-color: #96b97d;
justify-content: center;
align-items: center;
display: flex;
}
</style>
</head>
<body>
<div class="parent">
<div>
不宽高的水平垂直居中<br/>
不宽高的水平垂直居中<br/>
</div>
</div>
</body>
</html>