容器中的图像可以从其中心缩放吗?(Can an image in a container scale from its center?)

编程入门 行业动态 更新时间:2024-10-28 11:24:26
容器中的图像可以从其中心缩放吗?(Can an image in a container scale from its center?)

在这里,我有一个图像,可以在扩展浏览器窗口时进行缩放,直到达到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%);

更多推荐

本文发布于:2023-08-06 20:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1455387.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缩放   容器   图像   中心   center

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!