html - 在 div 中居中图像元素

标签 html css

我正在学习一些关于初学者 HTML 和 CSS 的教程。我试图将图像置于 div 的中心,但是当我将窗口的宽度缩小到某个像素时,图像右侧的边距越来越小。这是我用来演示的照片:https://imgur.com/Ihz0OeY .以下是 CSS 代码:

.bg-image {
  background-image: url("res/img/testbackground.jpg");
  filter: blur(8px);
  -webkit-filter: blur(8px);
  width: 100%;
  height: calc(100vh - 56px);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

bg-text {
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0, 0.4);
  color: white;
  position: relative;
  left:50%;
  top:50%;
  font-weight: bold;
  transform: translate(-50%, -150%);
  border: 3px solid #f1f1f1;
 width: 80%;
  padding: 20px;
 text-align: center;
}

.bg-text img {
  width:200px;
  display: block;
  margin-left: auto;
  margin-right: auto;
} 

我使用 position: relative 是因为如果我使用 absolute,当导航栏展开时文本不会被下推。 HTML 代码没什么特别的,我从 Bootstrap 获取的导航栏。

  <div class="bg-image"></div>
  <div class="bg-text">
      <img id ="1" src="res/img/dog.png" alt="">
       <h1>12345</h1>
       <p>ABCDEF</p>
   </div>

你们能帮帮我吗?非常感谢。

最佳答案

问题只是您的 img 元素在中心宽度处比屏幕尺寸大。使用流体宽度来解决这个问题:

.bg-text img {
  width:90%;
  display: block;
  margin: 0 auto;
} 

block 级元素默认总是左对齐,这意味着如果您不使用基于百分比的宽度告诉元素包含在窗口中,元素将保持其静态宽度(在本例中为 200px)即使窗口缩小超过该数字。因此,边距似乎在右侧缩小。如果您使用基于像素的宽度,最好将其声明为 max-width,并将基于百分比的宽度定义为后备,如下所示:

.bg-text img {
  width:100%;
  max-width:200px;
  display: block;
  margin: 0 auto;
}

这意味着只要父元素的宽度大于 200px,该元素就会有 200px 宽并且居中。如果父元素的宽度小于 200px,该元素将自动变为其父元素宽度的 100%。

关于html - 在 div 中居中图像元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56900575/

相关文章:

javascript - 使用溢出 :scoll,SVG 无法在 Div Wrapper 中滚动

css - 如何在 flex 4 的 css 文件中设置 backgroundImage 属性?

html - 表单中的文本区域不可点击输入字段。 Bootstrap 3

javascript - 如何在javascript中获取表格中复选框的值

html - col-md-4 div 中的图像不是全宽

javascript - jQuery 将选择选项移动到第二个位置

html - 在悬停时使 svg 图标颜色

javascript - 无法获取元素动画以等待 jquery 中的另一个元素动画

html - html中的“图层”,透明部分

javascript - 如何使图像表现得像文件输入?