如何在 div 中创建中心图像?

How to create center image in div?

我有分辨率为 1000px*1000px 的图像,

这是我的 html :

<style> 
 .test{
  width: 400px;
  height: 400px;
  }
</style>

<div class="test"> <img src="..."/> </div>
<div class="test"> <img src="..."/> </div>
<div class="test"> <img src="..."/> </div>
<div class="test"> <img src="..."/> </div>

如果原图是全身,我希望在div时只看到脸部。 我不知道怎么做。

谁能帮帮我? 提前致谢

这是您要搜索的内容吗:

.test img {
  position: absolute;
  top:50%; 
  left:50%;
  -webkit-transform:translate(-50%,-50%);
}

重写,这使容器内的较小图像居中,这是有效的 example

你可以试试这样的...

HTML

<div class="test"> <img src="http://placehold.it/300x150"/> </div>

CSS

.test{
    width: 400px;
    height: 400px;
    background-color: #000000;
  }

.test img {
    width:350px;
    height: 150px;
    display: block;
    margin: 0 auto;
}

JSFiddle

显然,这是基于您的代码,您可以根据需要调整宽度。

您还可以在很多地方进一步了解这一点。 W3.org 有一篇关于此的好文章。

N.B。这是基于您只想将图像水平居中的假设。让我们知道您是否也需要它垂直居中。

让我们从这个版本开始,然后看看我们会在哪里结束。 这是一个以 400x400px DIV 元素为背景的 1000x1000px 图像的示例。 你想用什么样的幻灯片?

div{
    background: url('http://curezone.com/upload/Members/New02/nasa1R3107_1000x1000.jpg');
    background-position: center; 
    width: 400px;
    height: 400px;
}
<html>
<body>
 <div>
 
 </div>
</body>
</html>

在你的情况下,你可以像这样玩数字(已编辑):

.test{
        width: 300px;
        height: 300px;
        border:5px solid red;
        position: relative;
        background: url('http://winniecooper.net/flores/pics/snow%20umbrella.jpg');
        background-position: 50% 75%;
        background-size: 1000px 1000px;
        -webkit-transition: background 1s;
        -moz-transition: background 1s;
        -o-transition: background 1s;
        transition: background 1s;
}
.test:hover{
        background-position: 0% 75%;
}
<div class="test">  </div>

更新:o)
根据您提供的 link,我可以大致解释它是如何完成的(或者我会这样做)。此网站有 DIV 500% 宽度分成 5 DIV 每个父 DIV 的 20% 宽度(所以全屏宽度,你将有 4 DIV 25% 宽度).每个 DIV 内部都有图像,其宽度为父 DIV 的 100%。 所以你一次只会看到一张图片。使用一些脚本你可以改变 master DIV 的位置。我会更改样式 属性 master DIV 的左值,并将过渡应用于那个 DIV ,这将使该更改动画化为幻灯片。

使用这个技巧。

  1. 让所有的<img>标签对同一张图片有一个src值(例如transparent-image.png)。使用图像编辑器,将图像 opacity 设置为零,从而使图像完全透明。此透明图像的大小应为 1px x 1px。

  2. 然后在所有 <img> 标签上设置内联样式,background-image 设置为您选择的图像。了解在 <img> 上设置的 src 值(透明-image.png,即 opacity 设置为零的图像)不会阻碍其自身 background-image 的可见性如内联样式中所定义。这是因为图像不透明度设置为零。

  3. 最后,在 <img> 标签上创建一个 css 规则,并将 background-position 设置为 center 垂直和 center 水平.例如;

    .test img { background-position: center center; }

下面是一个模板,将我解释的所有内容组合在一起。

HTML

<div class="test"> 
    <img src="transparent-image.png" style="background-image:url(image1.jpg)" /> 
</div>
<div class="test"> 
    <img src="transparent-image.png" style="background-image:url(image2.jpg)" /> 
</div>
<div class="test"> 
    <img src="transparent-image.png" style="background-image:url(image3.jpg)" /> 
</div>

CSS

.test {
    width: 400px;
    height: 400px;
}

.test img {
    background-position: center center; /* you can adjust this with values. Eg 50% 50% */
    background-repeat: no-repeat;
    background-size: cover;
}

祝你好运!