javascript - 在 div 中居中图像,如设置背景位置

标签 javascript jquery html css

有什么方法可以在 div 内完美居中设置标签,而不管该 div 的宽度和高度是多少?换句话说,我想在 div 标签内设置一个图像位置,如中心背景。例如:

.image-wrap {
  width: 50vw;
  height: 720px;
  background: url('some-images.jpg') no-repeat center center / auto 100%;
}

我想在 div 中设置一个图像,就像上面的背景一样,自动宽度和 100% 高度,这样图像中的所有重要内容都将位于 div 的中心。

<div class="image-wrap">
  <img src="some-images.jpg" alt="some image here"/>
</div>

非常感谢!

最佳答案

您可以使用 flex 属性轻松地将其居中。演示 here

.image-wrap {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;

  border: dotted 1px #CCC;
}
<div class="image-wrap">
  <img src="http://lorempixel.com/400/200" alt="some image here"/>
</div>

关于javascript - 在 div 中居中图像,如设置背景位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42240058/

相关文章:

html - CSS float : Why doesn't the second box shift to the left side of my floated box

html - 带有图像的 Outlook HTML 电子邮件

javascript - 使用 websocket 在浏览器和 java SE 项目之间传递数据

javascript - 如何修复 html 元素以跟随类或 div?

jquery - 鼠标悬停/鼠标离开 : 3rd image positioning and toggling on and off

jquery - 为什么第二次打不开 Bootstrap 模式对话框?

javascript - 使用 JavaScript 转换字符链(不再工作?)

javascript - `dest` 和 `dist` 有什么区别?

javascript - 在javascript中获取对象的值

html - 刷新时需要重置单选按钮