gpt4 book ai didi

css - 垂直对齐响应宽度和高度图像

转载 作者:技术小花猫 更新时间:2023-10-29 11:21:30 27 4
gpt4 key购买 nike

我有一个 div,它会随着屏幕的大小改变宽度。我还希望 div 的高度随着图像调整到最大高度,然后任何溢出的图像都将被隐藏。

到目前为止,我只能使用绝对定位使图像居中,但这意味着我还必须包含一个相同大小的占位符图像,以便 div 改变高度:

#test {
max-height: 400px;
width: 50%;
overflow: hidden;
position: relative;
}
#test .test-image {
width: 100%;
}
#test .vertical-align {
left: 0;
top: 50%;
position: absolute;
transform: translateY(-50%);
}
<div id="test">
<!-- this is a placeholder to make the div height expand / contract depending on the width -->
<img src="http://lorempixel.com/800/800/sports/1" class="test-image">

<!-- this is the vertically aligned image -->
<img src="http://lorempixel.com/800/800/sports/1" class="test-image vertical-align">
</div>

有什么方法可以使用相对定位来做到这一点,这样我就不需要包含占位符图像了吗?

我想到了以下内容,但它似乎不起作用,因为它似乎只是将图像移回到它开始的位置并从底部裁剪而不是居中:

#test {
max-height: 400px;
width: 50%;
overflow: hidden;
position: relative;
}
#test .test-image {
width: 100%;
}
#test .vertical-align {
margin-top: 50%;
position: relative;
transform: translateY(-50%);
}
<div id="test">
<!-- this is the vertically aligned image -->
<img src="http://lorempixel.com/800/800/sports/1" class="test-image vertical-align">
</div>

纯 css 可以吗?请只发布 css 解决方案 - 没有 js 答案。

谢谢

更新

我已经设法弄清楚为什么绝对有效但相对无效 - 当绝对时,top:50% 是父 div 的 50%,而当相对时,margin-top:50% 是图像高度的 50%,这就是为什么翻译只是将它移回到它的起始位置。

所以我想任何解决方案都是基于在应用变换之前将图像向下移动父级高度的 50%。我在 parent 身上玩过填充,但这似乎在任何一个地方都不起作用

最佳答案

我找到了一个使用 flex 的解决方案,希望你觉得它有用:

#test {
max-height: 400px;
width: 50%;
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
overflow:hidden;
}

#test .test-image {
width: 100%;
}
<div id="test">
<img src="http://lorempixel.com/800/800/sports/1" class="test-image">
</div>

更新:

我只是通过添加一个额外的 div 使其在 IE 11 中工作。也许这对你来说还不够,但我已经花了我所有的资源。

#container {
display: flex;
}

#test {
max-height: 400px;
overflow: hidden;
width: 50%;
align-items: center;
align-content:center;
display: flex;
}

#test .test-image {
width: 100%;
}
<div id="container">
<div id="test">
<img src="http://lorempixel.com/800/800/sports/1" class="test-image">
</div>
</div>

关于css - 垂直对齐响应宽度和高度图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37480926/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com