CSS(层叠样式表)是一种用于描述HTML文档样式的语言。图片居中是指将图片在容器内水平或垂直居中对齐。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片居中示例</title>
<style>
.container {
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<img src="example.jpg" alt="示例图片">
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片居中示例</title>
<style>
.container {
display: flex;
align-items: center;
height: 100vh; /* 使容器高度占满整个视口 */
}
</style>
</head>
<body>
<div class="container">
<img src="example.jpg" alt="示例图片">
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片居中示例</title>
<style>
.container {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 100vh; /* 使容器高度占满整个视口 */
}
</style>
</head>
<body>
<div class="container">
<img src="example.jpg" alt="示例图片">
</div>
</body>
</html>
原因:
解决方法:
height: 100vh
。text-align: center
或 display: flex
。通过以上方法,你可以轻松实现图片在容器内的水平和垂直居中。
领取专属 10元无门槛券
手把手带您无忧上云