CSS - 始终居中图像

CSS - Center Image at all times

我在 Div.

中使用了一张图片

我想知道如何始终将图像垂直和水平居中。

目前我拉伸的时候好像是从左上角开始拉伸,有什么办法可以一直居中

我已经在网上搜索并尝试了各种方法,但似乎无法正常工作。

这是我的 html:

<div class="container"></div>

这是我的 css:

.container {
    width: 100%;
    height: 75vh;
    background-image: url("http://i.stack.imgur.com/2OrtT.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    background-position: 50% 50%;
}

感谢任何帮助或建议,提前致谢。

EDIT you can see that when I stretch the browser, it seems to be stretching from the left, i want to be able to have the Image centered so it stretches from all sides equally*

background-position: center 将使您的图像在垂直和水平居中对齐。

检查以下代码段:

* {
  margin: 0;
  padding: 0;
}
.container {
  width: 100%;
  height: 100vh;
  background-image: url("http://i.stack.imgur.com/2OrtT.jpg");
  background-repeat: no-repeat;
  background-position: center;
}
<div class="container"></div>

我得到了解决方案..!

这是您的 html 文件:

<div class="container"></div>

CSS 文件:

.container {
width: 100%;
height: 75vh;
position: absolute;
margin: auto;
background-image: url("http://i.stack.imgur.com/2OrtT.jpg");
background-size: cover;
background-repeat: no-repeat;
background-position: 50% 50%;
top: 0;
left: 0;}

这里正在工作demo

.container {
    width: 100%;
    height: 75vh;
    background-image: url("http://i.stack.imgur.com/2OrtT.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
  background-size:auto;
}
<div class="container"></div>

HTML :

<div class="container"></div>

CSS :

.container{width: 100%;height: 75vh;position: absolute;margin: auto;background-image: url("http://i.stack.imgur.com/2OrtT.jpg");background-size: cover;background-repeat: no-repeat;background-position: 50% 50%;top: 0;left: 0;}