文字水平居中
<style>
.sample1 {
text-align: center;
border: 1px solid;
width: 500px;
}
</style>
<body>
<div class="sample1">
<span>
我是文字
</span>
</div>
</body>

图片水平垂直居中
<style>
.sample1 {
display: flex;
justify-content: center;
align-items: center;
border: 1px solid;
width: 500px;
}
</style>
<body>
<div class="sample1">
<img src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike180%2C5%2C5%2C180%2C60/sign=e90f5c043bd12f2eda08a6322eabbe07/9358d109b3de9c8243bbc45c6181800a18d84302.jpg"
width="50px" height="50px" />
</div>
</body>

图片与文字水平垂直居中
代码同上
<style>
.sample1 {
display: flex;
justify-content: center;
align-items: center;
border: 1px solid;
width: 500px;
}
</style>
<body>
<div class="sample1">
<span>我是文字</span>
<img src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike180%2C5%2C5%2C180%2C60/sign=e90f5c043bd12f2eda08a6322eabbe07/9358d109b3de9c8243bbc45c6181800a18d84302.jpg"
width="50px" height="50px" />
</div>
</body>

DIV相对于页面垂直居中并且响应式
<style>
.sample1 {
left:50%; top:50%; transform:translate(-50%,-50%); position:absolute;
border: 1px solid;
}
</style>
<body>
<div class="sample1">
<span>我是文字</span>
<img src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike180%2C5%2C5%2C180%2C60/sign=e90f5c043bd12f2eda08a6322eabbe07/9358d109b3de9c8243bbc45c6181800a18d84302.jpg"
width="50px" height="50px" />
</div>
</body>

视口绝对垂直居中 常用于弹出框
<style>
.container {
position: relative;
}
.sample1 {
border: 1px solid;
width: 50%;
height: 50%;
overflow: auto;
margin: auto;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 999;
}
</style>
<body>
<div class="container">
<div class="sample1">
</div>
</div>
</body>

图片根据父元素自定义大小水平垂直居中
<style>
.sample1 {
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
position: absolute;
border: 1px solid;
width: 400px;
height: 300px;
}
img {
width: 50%;
height: auto;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
</style>
<body>
<div class="sample1">
<img
src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike180%2C5%2C5%2C180%2C60/sign=e90f5c043bd12f2eda08a6322eabbe07/9358d109b3de9c8243bbc45c6181800a18d84302.jpg" />
</div>
</body>

网友评论