html - 为什么 png 图像不在父 div 中居中?

标签 html css

<分区>

我正在尝试使图像在容器中居中。

根据我的理解,将容器的 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/

上一篇:css - `overflow-block` 和 `overflow`(和 `block-overflow`)有什么区别?

下一篇:html - 使用 object-fit : contain 将 Div 附加到全屏居中图像的一 Angular

相关文章:

javascript - 根据选择值添加/删除表行

html - 为什么我的字体大小不会相对于屏幕大小发生变化?

javascript - 如何在固定元素上设置 IntroJS 步骤?

特定屏幕分辨率范围缺少 CSS 样式?

javascript - 如何在打开下拉菜单时隐藏当前选定的选项

html - 单击图像时用于调用操作的_正确_ html 元素是哪个?

javascript - 如何将 Html 表更改为链接

HTML 导航栏延伸至底部

html - 位置 :fixed and overflow:visible property in css 之间的冲突

html - Firefox 中的文本对齐