将html元素的宽度设置为兄弟的宽度
发布时间:2020-12-14 19:46:38 所属栏目:资源 来源:网络整理
导读:我有一个稍微不寻常的CSS挑战需要克服. 我有一个两列布局,其中左列的宽度由主图像的宽度设置,右边允许填充剩余的空间.主图像下方有一个容器,其自然宽度可能大于主图像.但是,我希望这个div与主图像的宽度相同,并且要隐藏溢出.以下是我尝试这样做的努力: .out
我有一个稍微不寻常的CSS挑战需要克服. 我有一个两列布局,其中左列的宽度由主图像的宽度设置,右边允许填充剩余的空间.主图像下方有一个容器,其自然宽度可能大于主图像.但是,我希望这个div与主图像的宽度相同,并且要隐藏溢出.以下是我尝试这样做的努力: .outer { margin-right: 5px; position: relative; } .left { float: left; } .right { width: auto; overflow: hidden; } .contentOuter { overflow: hidden; } .content { width: 500px; } .inner { background-color: grey; color: white; width: 100%; height: 150px; } <div class="outer left"> <div class="image"><img src="http://placehold.it/350x150" /> 但正如您所看到的,无论我尝试什么,.contentOuter都会延伸到其内容的宽度. 我有一个主要的警告是,除了具有固定宽度的.content之外,我不希望我的CSS中有任何其他硬编码宽度;一切都应该是完全流动的,并且列的尺寸由.image img的尺寸决定. 所以,我在视觉上看起来像这样,但没有.content上的硬编码最大宽度: .outer { margin-right: 5px; position: relative; } .left { float: left; } .right { width: auto; overflow: hidden; } .contentOuter { overflow: hidden; } .content { max-width: 350px; /* Hard-coded for demo purposes */ } .inner { background-color: grey; color: white; width: 100%; height: 150px; } <div class="outer left"> <div class="image"><img src="http://placehold.it/350x150" /> 最佳答案 解决这个问题的一种快速方法是简单地使用一些jQuery.它只需要两行代码即可实现. var imgWidth = $('.image').width(); $('.content').width(imgWidth); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |