CSS 在 Div 中居中超大图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14562457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Center Oversized Image in Div
提问by Tom
I have been trying to sort out how to center an oversized image within a div using css only.
我一直在尝试解决如何仅使用 css 在 div 中居中放置超大图像。
We are using a fluid layout, so the width of the image containers varies as the page width does (height of div is fixed). The image sits within a div, withvalue an inset boxshadow so as to appear as if you are looking through the page at the image.
我们使用的是流体布局,因此图像容器的宽度随着页面宽度的变化而变化(div 的高度是固定的)。图像位于一个 div 内,带有插入框阴影的值,以便看起来好像您正在浏览图像的页面。
The image itself has been sized to fill the surrounding div at its widest possible value (the design has a max-width
value).
图像本身的大小已调整为以尽可能宽的值填充周围的 div(设计有一个max-width
值)。
It is pretty easy to do if the image is smaller than the surrounding div:
如果图像比周围的 div 小,这很容易做到:
margin-left: auto;
margin-right: auto;
display: block;
But when the image is larger than the div it simply starts at the left edge and is off center to the right (we are using overflow: hidden
).
但是当图像大于 div 时,它只是从左边缘开始,向右偏离中心(我们正在使用overflow: hidden
)。
We could assign a width=100%
, but browsers do a lousy job of resizing images and the web design centers around high quality imagery.
我们可以指定一个width=100%
,但是浏览器在调整图像大小方面做得很糟糕,而网页设计则以高质量图像为中心。
Any ideas on centering the image so that overflow:hidden
cuts off both edges evenly?
关于将图像居中以便overflow:hidden
均匀地切断两个边缘的任何想法?
回答by hyounis
Try something like this. This should center any huge element in the middle vertically and horizontally with respect to its parent no matter both of their sizes.
尝试这样的事情。无论它们的大小如何,这都应该相对于其父级垂直和水平居中中间的任何巨大元素。
.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;
}
回答by yunzen
This is an old Q, but a modern solution without flexbox or position absolute works like this.
这是一个旧的 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>
So why does it work?
At first glance it seems that we shift 50% to the right and then 50% to the left again. That would result in zero shift, so what?
But the 50% are not the same, because context is important. If you use relative units, a margin will be calculated as percentage of the width of the parentelement, while the transform will be 50% relative to the sameelement.
那么它为什么有效呢?
乍一看,我们似乎向右移动了 50%,然后又向左移动了 50%。那会导致零偏移,那又怎样?
但 50% 不一样,因为上下文很重要。如果使用相对单位,边距将计算为父元素宽度的百分比,而变换将是相对于同一元素的50% 。
We have this situation before we add the CSS
我们在添加 CSS 之前就有这种情况
+-------------------------------------------+
| Parent element P of E |
| |
+-----------------------------------------------------------+
| Element E |
+-----------------------------------------------------------+
| |
+-------------------------------------------+
With the added style margin-left: 50%
we have
添加样式后,margin-left: 50%
我们有
+-------------------------------------------+
| Parent element P of E |
| |
| +-----------------------------------------------------------+
| | Element E |
| +-----------------------------------------------------------+
| | |
+---------------------|---------------------+
|========= a ========>|
a is 50% width of P
And the transform: translateX(-50%)
shifts back to the left
然后transform: translateX(-50%)
向左移动
+-------------------------------------------+
| Parent element P of E |
| |
+-----------------------------------------------------------+
| Element E | |
+-----------------------------------------------------------+
|<============ b ===========| |
| | |
+--------------------|----------------------+
|========= a =======>|
a is 50% width of P
b is 50% width of E
Unfortunately this does only work for horizontal centering as the margin percentage calculation is always relative to the width. I.e. not only margin-left
and margin-right
, but also margin-top
and margin-bottom
are calculated with respect to width.
不幸的是,这仅适用于水平居中,因为边距百分比计算始终与宽度相关。即不仅margin-left
and margin-right
,而且margin-top
andmargin-bottom
是根据宽度计算的。
Browser compatibility should be no problem: https://caniuse.com/#feat=transforms2d
浏览器兼容性应该没问题:https: //caniuse.com/#feat=transforms2d
回答by Guffa
Put a large div inside the div, center that, and the center the image inside that div.
将一个大 div 放在 div 内,将其居中,并将图像置于该 div 内的中心。
This centers it horizontally:
这将它水平居中:
HTML:
HTML:
<div class="imageContainer">
<div class="imageCenterer">
<img src="http://placekitten.com/200/200" />
</div>
</div>
CSS:
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;
}
Demo: http://jsfiddle.net/Guffa/L9BnL/
演示:http: //jsfiddle.net/Guffa/L9BnL/
To center it vertically also, you can use the same for the inner div, but you would need the height of the image to place it absolutely inside it.
要使其垂直居中,您可以对内部 div 使用相同的内容,但您需要图像的高度才能将其绝对放置在其中。
回答by Ezeewei
Late to the game, but I found this method is extremely intuitive. https://codepen.io/adamchenwei/pen/BRNxJr
游戏迟到了,但我发现这种方法非常直观。 https://codepen.io/adamchenwei/pen/BRNxJr
CSS
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;
}
HTML
HTML
<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>
回答by leatherHymanet4
Do not use fixed or an explicit width or height to the image tag. Instead, code it:
不要对图像标签使用固定或明确的宽度或高度。相反,编码它:
max-width:100%;
max-height:100%;
回答by Shain Lafazan
i'm a huge fan of making an image the background of a div/node -- then you can just use the background-position: center
attribute to center it regardless of screen size
我非常喜欢将图像作为 div/node 的背景——那么background-position: center
无论屏幕大小如何,您都可以使用该属性将其居中
回答by Панайот Толев
The width and height are only for example:
宽度和高度仅为示例:
parentDiv{
width: 100px;
height: 100px;
position:relative;
}
innerDiv{
width: 200px;
height: 200px;
position:absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
It has to work for you if the left and top of your parent div are not the very top and left of the window of your screen. It works for me.
如果您的父 div 的左侧和顶部不是屏幕窗口的最顶部和左侧,它必须为您工作。这个对我有用。
回答by Cezar D.
I found this to be a more elegant solution, without flex:
我发现这是一个更优雅的解决方案,没有 flex:
.wrapper {
overflow: hidden;
}
.wrapper img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* height: 100%; */ /* optional */
}
回答by volt
One option you can use is object-fit: cover
it behaves a bit like background-size: cover
. More on object-fit.
您可以使用的一个选项是object-fit: cover
它的行为有点像background-size: cover
. 更多关于object-fit。
ignore all the JS below, that's just for the demo.
忽略下面所有的 JS,这只是为了演示。
The key here is that you need to set the image inside a wrapper and give it the following properties.
这里的关键是您需要在包装器中设置图像并为其提供以下属性。
.wrapper img {
height: 100%;
width: 100%;
object-fit: cover;
}
I've created a demo below where you change the height / width of the wrapper and see in play. The image will always be vertically and horizontally centered. It will take up 100% of its parent width and height, and will not be stretched / squashed. This means that the aspect ratio of the image is maintained. The changes are applied by zooming in / out instead.
我在下面创建了一个演示,您可以在其中更改包装器的高度/宽度并查看实际效果。图像将始终垂直和水平居中。它将占据其父级宽度和高度的 100%,并且不会被拉伸/挤压。这意味着图像的纵横比保持不变。更改是通过放大/缩小来应用的。
The only downside to object-fit
is that it doesn't workon IE11.
唯一的缺点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>