<分区>
<分区>
我正在尝试使图像在容器中居中。
根据我的理解,将容器的 position
设置为“relative
”,将 text-align 属性设置为 center 应该
垂直居中的 block 级元素有它们的 position
属性设置为 absolute
。但是,为什么我的情况不是这样
代码?
.first-container {
background-color: yellow;
height: 100%;
position: relative;
text-align: center;
width: 100%;
}
.mountain {
position: absolute;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Playground</title>
</head>
<body>
<div class="first-container">
<img class="mountain" src="images/mountain.png" alt="">
</div>
<div class="second-container">
</div>
<div class="third-container">
</div>
</body>
</html>
我希望山图像位于第一个容器的中心,我将背景颜色设置为黄色以便于区分。
最佳答案
当您使用 position: absolute
时在带有 position: relative
的容器中的图像上,您的图像是在容器的中心。或者,更具体地说,以图像的左上角像素为中心。
为了使图像居中,使图像的中心位于包含元素的中心,您要设置一个 margin-left
图像宽度的负一半。这可以在下面看到,图像是 100px
宽,有margin-left: -50px
:
.first-container {
background-color: yellow;
height: 100%;
position: relative;
text-align: center;
width: 100%;
}
.mountain {
position: absolute;
margin-left: -50px;
}
<div class="first-container">
<img class="mountain" src="https://placehold.it/100" alt="">
</div>
假设您设置了 width
在图像本身上,您实际上可以结合使用 CSS 变量和 calc()
为了确定这个 margin ,用 width: var(--image-width)
和 margin-left: calc(var(--image-width) / -2)
在图像上。
:root {
--image-width: 100px;
}
.first-container {
background-color: yellow;
height: 100%;
position: relative;
text-align: center;
width: 100%;
}
.mountain {
position: absolute;
width: var(--image-width);
margin-left: calc(var(--image-width) / -2);
}
<div class="first-container">
<img class="mountain" src="https://placehold.it/100" alt="">
</div>
关于html - 为什么 png 图像不在父 div 中居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57764885/