我的HTML
<div ID="container"> <img src="http://silberschauer.de/img/pre/045.jpg" /></div>
在CSS
#container {position:absolute;top:1em;left:1em;bottom:2em; wIDth:30%;background:#0f0;overflow:hidden;}#container img {wIDth:100%;}
https://jsfiddle.net/t4um60k1/8/
如果(并且只是)容器在y轴上比使用CSS的图像更小,是否可以使图像剪辑顶部和底部相等?
编辑:
如果您的解决方案在任何情况下都在图像上方提供绿色区域,您就不明白这个问题.
Is it possible to have the image clip top and bottom equally while staying top-aligned if the container gets smaller in v-axis than the image with CSS?
是的,这可以通过CSS整齐有效地完成. FlexBox非常适合这类事情.
不需要Js.没有对HTML进行任何更改.
将其添加到您的CSS:
#container { display: flex; /* new */ flex-direction: column; /* new */ justify-content: space-between; /* new */ position: absolute; top: 1em; left: 1em; bottom: 2em; wIDth: 30%; background: #0f0; overflow: hIDden;}#container::before,#container::after { content: '';}#container img { wIDth: 100%; flex-shrink: 0;}
https://jsfiddle.net/t4um60k1/10/
说明
我们使用flexBox在垂直轴(flex-direction:column)上对齐图像.
然后我们告诉flex容器任何子元素(也称为flex项)将作为空格对齐.
对于justify-content: space-between
,柔性项目均匀分布,第一个项目在容器的一个边缘对齐,最后一个项目在相对边缘对齐.在这种情况下,因为我们在列方向,我们谈论的是顶部和底部边缘.
为了确保图像保持在中间,我们使用伪元素在每一端创建“幻影”flex项.
但是,为什么采取这些额外的步骤来使图像居中,当正确的内容:中心会以较少的麻烦完成工作?
因为问题的第二个要求是图像在超过容器高度时必须是顶部对齐的.
使用justify-content:center,图像将始终保持居中.
但根据空间规则,如果d性项目溢出容器,空间介于两者之间切换到d性开始,这会使图像与顶部对齐(下面有更多详细信息).
最后,由于d性项目通常是灵活的,因此对图像应用flex-shrink:0以确保它不会从其原始大小缩小.
从空间切换到flex-start
从规格:
space-between
Flex items are evenly distributed in the line. If the leftover
free-space is negative or there is only a single flex item on the
line,this value is IDentical toflex-start
.center
Flex items are packed toward the center of the line. … If the leftover
free-space is negative,the flex items will overflow equally in both
directions.(emphasis mine)
source: 07002
请注意,所有主流浏览器都支持flexBox,except IE 8 & 9.某些最近的浏览器版本,例如Safari 8和IE10,需要vendor prefixes.要快速添加所需的所有前缀,请在左侧面板中发布CSS:Autoprefixer.
总结以上是内存溢出为你收集整理的html – 如何在CLIP上对图像进行y中心,但如果它小于其容器,则让它保持顶部对齐?全部内容,希望文章能够帮你解决html – 如何在CLIP上对图像进行y中心,但如果它小于其容器,则让它保持顶部对齐?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)