如何让图片高度与包含引用及署名的兄弟div保持一致?
如何让图片高度与包含引用内容的兄弟div完全一致?
先看最初尝试的代码,想用flex布局让图片和文本div等高:
.fancyquote { display: flex; align-items: stretch; } img { height: 100%; object-fit: cover; }
<div class="fancyquote"> <img src="https://placehold.co/256x256?text=Author\nPhoto"/> <div> <blockquote>Some people have a way with words, and other people...oh, uh, not have way.</blockquote> <cite>Steve Martin</cite> </div> </div>
但这个方案有个局限:只有给图片手动设置宽度时,高度才会跟着兄弟div拉伸,没法自动匹配高度。
解决方法
给图片套一个容器,利用定位让图片填满容器,而容器会被flex布局自动拉伸到和文本div一样的高度:
.fancyquote { display: flex; align-items: stretch; } .img-wrap { position: relative; overflow: auto; /* 可根据需求给容器设置宽度,比如 width: 200px; 控制图片区域宽度 */ } img { position: absolute; top: 0; right: 0; left: 0; bottom: 0; object-fit: cover; /* 保证图片比例不变,避免拉伸变形 */ }
<div class="fancyquote"> <div class="img-wrap"> <img src="https://placehold.co/256x256?text=Author\nPhoto"/> </div> <div> <blockquote>Some people have a way with words, and other people...oh, uh, not have way.</blockquote> <cite>Steve Martin</cite> </div> </div>
原理很简单:flex布局的align-items: stretch会让所有flex子项(.img-wrap和文本div)高度一致,绝对定位的图片会填满.img-wrap的整个空间,这样图片高度就和文本div完全匹配了,不用依赖图片自身的宽度设置。
内容的提问来源于stack exchange,提问作者Dan Grahn
相关产品推荐
相关产品推荐

