在 Div 中居中超大的图像

我一直试图整理出如何在一个 div 中只使用 css 来居中超大尺寸的图像。

我们使用的是流式布局,因此图像容器的宽度随着页面宽度的变化而变化(div的高度是固定的)。该图像位于一个div中,带有值的插入框影,这样看起来就好像你正在通过页面查看图像一样。

图像本身的大小已被调整为以尽可能宽的值填充周围的div(该设计有max-width值)。

如果图像比周围的div小,这很容易做到:

margin-left: auto;
margin-right: auto;
display: block;

但当图像比div大时,它只是从左边缘开始,偏离中心向右(我们使用overflow: hidden)。

我们可以分配width=100%,但浏览器在调整图像大小方面做得很糟糕,而网页设计的中心是高质量的图像。

有什么关于图像居中的想法,以便overflow:hidden均匀地切断两个边缘?

193217 次浏览

在div中放置一个大的div,居中,并在该div中放置图像的居中。

这将使它水平居中:

HTML:

<div class="imageContainer">
<div class="imageCenterer">
<img src="http://placekitten.com/200/200" />
</div>
</div>

CSS:

.imageContainer {
width: 100px;
height: 100px;
overflow: hidden;
position: relative;
}
.imageCenterer {
width: 1000px;
position: absolute;
left: 50%;
top: 0;
margin-left: -500px;
}
.imageCenterer img {
display: block;
margin: 0 auto;
}

演示:http://jsfiddle.net/Guffa/L9BnL/

为了垂直居中,你也可以对内部div使用相同的方法,但你需要将图像的高度完全置于其中。

宽度和高度仅为示例:

parentDiv{
width: 100px;
height: 100px;
position:relative;
}
innerDiv{
width: 200px;
height: 200px;
position:absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}

如果你的父div的左边和顶部不是你屏幕窗口的最上面和左边,它必须为你工作。这对我很管用。

试试这样的方法。这将使任何巨大的元素在垂直和水平方向上处于中间的中央,无论它们的大小如何。

.parent {
position: relative;
overflow: hidden;
//optionally set height and width, it will depend on the rest of the styling used
}


.child {
position: absolute;
top: -9999px;
bottom: -9999px;
left: -9999px;
right: -9999px;
margin: auto;


}

我是一个巨大的粉丝,使一个div/节点的背景图像-然后你可以使用background-position: center属性居中,不管屏幕大小

不要对图像标签使用固定的或显式的宽度或高度。相反,编写如下代码:

      max-width:100%;
max-height:100%;

例:http://jsfiddle.net/xwrvxser/1/

这是一个老的Q,但是没有flexbox或绝对位置的现代解决方案是这样的。

margin-left: 50%;
transform: translateX(-50%);

.outer {
border: 1px solid green;
margin: 20px auto;
width: 20%;
padding: 10px 0;
/*   overflow: hidden; */
}


.inner {
width: 150%;
background-color: gold;
/* Set left edge of inner element to 50% of the parent element */
margin-left: 50%;
/* Move to the left by 50% of own width */
transform: translateX(-50%);
}
<div class="outer">
<div class="inner">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos exercitationem error nemo amet cum quia eaque alias nihil, similique laboriosam enim expedita fugit neque earum et esse ad, dolores sapiente sit cumque vero odit! Ullam corrupti iure eum similique magnam voluptatum ipsam. Maxime ad cumque ut atque suscipit enim quidem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi impedit esse modi, porro quibusdam voluptate dolores molestias, sit dolorum veritatis laudantium rem, labore et nobis ratione. Ipsum, aliquid totam repellendus non fugiat id magni voluptate, doloribus tenetur illo mollitia. Voluptatum.</div>
</div>

那么为什么它有效呢?
乍一看,我们似乎向右移动了50%,然后又向左移动了50%。这会导致零位移,那又怎样?
但这50%的人是不一样的,因为背景很重要。如果你使用相对单位,边框将被计算为元素宽度的百分比,而变换将是相对相同元素的50%

在添加CSS之前,我们就有这种情况

       +---------------------------+
| Parent element P of E     |
|                           |
+-----------------------------------------+
| Element E                               |
+-----------------------------------------+
|                           |
+---------------------------+

通过添加样式margin-left: 50%,我们有

       +---------------------------+
| Parent element P of E     |
|                           |
|             +-----------------------------------------+
|             | Element E                               |
|             +-----------------------------------------+
|             |             |
+-------------|-------------+
|>>>>> a >>>>>|
           

a is 50% width of P

并且transform: translateX(-50%)移回左边

       +---------------------------+
| Parent element P of E     |
|                           |
+-----------------------------------------+
| Element E         |                     |
+-----------------------------------------+
|<<<<<<<<< b <<<<<<<|              |
|            |              |
+------------|--------------+
|>>>>> a >>>>|
           

a is 50% width of P
b is 50% width of E

不幸的是,这只适用于水平居中,因为边际百分比计算总是相对于宽度。即,不仅margin-leftmargin-right,而且margin-topmargin-bottom都是根据宽度计算的。

浏览器兼容性应该没有问题: https://caniuse.com/#feat=transforms2d < / p >
虽然是后期的游戏,但我发现这个方法非常直观。 https://codepen.io/adamchenwei/pen/BRNxJr < / p >

CSS

.imageContainer {
border: 1px black solid;


width: 450px;
height: 200px;
overflow: hidden;
}
.imageHolder {
border: 1px red dotted;


height: 100%;
display:flex;
align-items: center;
}
.imageItself {
height: auto;
width: 100%;
align-self: center;


}

超文本标记语言

<div class="imageContainer">
<div class="imageHolder">
<img class="imageItself" src="http://www.fiorieconfetti.com/sites/default/files/styles/product_thumbnail__300x360_/public/fiore_viola%20-%202.jpg" />
</div>
</div>

我发现这是一个更优雅的解决方案,没有弹性:

.wrapper {
overflow: hidden;
}
.wrapper img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* height: 100%; */ /* optional */
}

你可以使用的一个选项是object-fit: cover,它的行为有点像background-size: cover。更多关于object-fit

忽略下面所有的JS,这只是为了演示。

这里的关键是需要在包装器中设置图像,并为其提供以下属性。

.wrapper img {
height: 100%;
width: 100%;
object-fit: cover;
}

我在下面创建了一个演示,您可以在其中更改包装器的高度/宽度,并在播放中看到。图像将始终处于垂直和水平居中。它将占据其父宽和高的100%,并且不会被拉伸/压扁。这意味着图像的纵横比得到了保持。这些变化是通过放大/缩小来应用的。

object-fit唯一的缺点是它在IE11上不工作

// for demo only
const wrapper = document.querySelector('.wrapper');
const button = document.querySelector('button');
const widthInput = document.querySelector('.width-input');
const heightInput = document.querySelector('.height-input');




const resizeWrapper = () => {
wrapper.style.width = widthInput.value + "px";
wrapper.style.height = heightInput.value + "px";
}


button.addEventListener("click", resizeWrapper);
.wrapper {
overflow: hidden;
max-width: 100%;
margin-bottom: 2em;
border: 1px solid red;
}


.wrapper img {
display: block;
height: 100%;
width: 100%;
object-fit: cover;
}
<div class="wrapper">
<img src="https://i.imgur.com/DrzMS8i.png">
</div>




<!-- demo only -->
<lable for="width">
Width: <input name="width" class='width-input'>
</lable>
<lable for="height">
height: <input name="height" class='height-input'>
</lable>
<button>change size!</button>

基于@yunzen的精彩回答:

我猜很多搜索这个话题的人都试图用一个大图像作为“英雄”。背景图像,例如在主页上。在这种情况下,他们通常希望文本出现在图像上,并在移动设备上缩放。

下面是这样一个背景图像的完美CSS(在<img>标签上使用它):

/* Set left edge of inner element to 50% of the parent element */
margin-left: 50%;


/* Move to the left by 50% of own width */
transform: translateX(-50%);


/* Scale image...(101% - instead of 100% - avoids possible 1px white border on left of image due to rounding error */
width: 101%;


/* ...but don't scale it too small on mobile devices - adjust this as needed */
min-width: 1086px;


/* allow content below image to appear on top of image */
position: absolute;
z-index: -1;


/* OPTIONAL - try with/without based on your needs */
top: 0;


/* OPTIONAL - use if your outer element containing the img has "text-align: center" */
left: 0;

基于@Guffa的答案
因为我浪费了2个多小时来居中一个非常宽的图像,
对于我来说,图像尺寸为2500x100px, viewport为1600x1200或全高清1900x1200 作品像这样居中:

 .imageContainer {
height: 100px;
overflow: hidden;
position: relative;
}
.imageCenter {
width: auto;
position: absolute;
left: -10%;
top: 0;
margin-left: -500px;
}
.imageCenter img {
display: block;
margin: 0 auto;
}

我希望这能帮助其他人更快地完成任务:)

它很简单,一些伸缩和溢出设置为隐藏。

enter image description here

<!DOCTYPE html>
<html lang="en">
<head>
<style>
div {
height: 150px;
width: 150px;
border: 2px solid red;
        

overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div>
<img src="sun.jpg" alt="">
</div>
</body>
</html>