在这里,我有一个图像,可以在扩展浏览器窗口时进行缩放,直到达到600px高,即其父容器的最大高度。 此时,图像相对于图像顶部被裁剪。 是否可以将图像垂直居中放在其父容器中,以便图像从其中心缩放? 它需要保留图像,而不是背景图像。
<html> <head> <meta charset="utf-8" /> <style type="text/css"> .full-width { max-height: 600px; overflow: hidden; } img.full { width: 100%; display: block; } </style> </head> <body> <section class="full-width"> <img class="full" src="http://toprival.com/temp/panda/images/panda.jpg" /> </section> </body>Here I have an image that scales as you widen the browser window until it reaches 600px tall, the maximum height of its parent container. At this point, the image is cropped relative to the top of the image. Is it possible to have the image vertically centered in its parent container, so that the image scales from its center? It needs to remain an image, and not a background image.
<html> <head> <meta charset="utf-8" /> <style type="text/css"> .full-width { max-height: 600px; overflow: hidden; } img.full { width: 100%; display: block; } </style> </head> <body> <section class="full-width"> <img class="full" src="http://toprival.com/temp/panda/images/panda.jpg" /> </section> </body>最满意答案
你可以这样做:
img.full { width: 100%; display: block; top: 50%; transform: translateY(-50%); }它将图像向上移动到容器高度的50%,然后将其向上移动50%的图像高度,从而使其垂直居中。
但是,容器元素需要一个确定的高度和relative的position设置才能使其工作。
...你可以对水平居中做同样的事情: left: 50%; transform: translateX(-50%); left: 50%; transform: translateX(-50%);
you can do this:
img.full { width: 100%; display: block; top: 50%; transform: translateY(-50%); }It moves the image top down 50% of the container height and then moves it back up by 50% of the image height, thereby centering it vertically.
However, the container element needs a defined height and a position setting of relative for this to work.
...and you can do the same for horizontal centering: left: 50%; transform: translateX(-50%);
更多推荐
发布评论