我有一个文本图像组件,如果文本较少(条件一)(对于较大的屏幕),我需要将文本与 float 图像中间垂直对齐。如果文本较多,则让它环绕 float 图像(条件二)(同样适用于较大的屏幕)。我怎样才能在 CSS 中做到这一点,或者我们是否需要 Javascript 来做到这一点?这是fiddle 。我的条件一和条件二都应该有效。
.clearfix { clear: both; }
.text-img { padding-left: 15px; padding-right: 15px; }
.text-img .info-box .info--body p { max-width: none; }
.text-img .info-box { text-align: justify; }
.text-img .stock-img { width: 100%; }
@media (min-width: 992px) {
.text-img.text-right .stock-img { width: 50%; float: left; }
.text-img.text-right .stock-img { padding-right: 15px; padding-bottom: 15px; }
.text-img.text-left .stock-img { width: 50%; float: right; }
.text-img.text-left .stock-img { padding-left: 15px; padding-bottom: 15px; }
}
<div class="clearfix text-img text-left">
<img src="https://cdn0.vox-cdn.com/thumbor/gvDQZLtlEM7U99rmTEdMoUtLRJU=/0x96:2039x1243/1600x900/cdn0.vox-cdn.com/uploads/chorus_image/image/50319283/ipad1_2040.0.0.jpg" alt="iPad" class="img-responsive stock-img" />
<div class="info-box">
<header class="info--header">
<h3 class="h3">The science of today is the technology of tomorrow.</h3>
</header>
<div class="info--body">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc semper urna nec lectus malesuada tincidunt. Aenean faucibus, nulla sed luctus tempus, purus libero vestibulum velit, et blandit odio nunc ac quam. Donec tellus tellus, venenatis ac diam nec, sodales viverra orci.</p>
</div>
</div>
</div>
我希望最终的输出是这样的,它满足我的条件:
嗯,给出的答案是正确的,这不能仅通过 CSS 来解决,所以我必须想出 jQuery 解决方案。对于那些寻找此类场景解决方案的人,这里是解决我的问题的 jQuery 代码:
$(document).ready(function() {
$(".text-img").each( function() {
var cH = parseInt( $( this ).height() );
var tH = parseInt( $( this ).find('.info-box').height() );
if( tH < cH ) {
var pt = ( cH - tH ) / 2;
$( this ).find('.info-box').css({
"padding-top" : pt + "px"
});
}
});
});
最佳答案
当您在较小的屏幕中时,请使用 flexbox 布局。
@media (min-width: 992px) {
.text-left {
display: flex;
align-items: center;
justify-content: center;
}
.text-left img {
max-width: 50%;
height: auto;
margin-right: 10px;
}
}
预览
关于javascript - 当文本较少时,将文本垂直对齐到图像中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41464302/