HTML   发布时间:2022-04-14  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了html – 将元素的宽度设置为兄弟的宽度大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个稍微不寻常的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" />
  </div>
  <div class="contentOuter">
    <div class="content">
      <img src="http://placehold.it/500x50" />
    </div>
  </div>
</div>
<div class="outer right">
  <div class="inner">
    Hello world!
  </div>
</div>

正如您所看到的,无论我尝试什么,.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" />
  </div>
  <div class="contentOuter">
    <div class="content">
      <img src="http://placehold.it/500x50" />
    </div>
  </div>
</div>
<div class="outer right">
  <div class="inner">
    Hello world!
  </div>
</div>

解决方法

解决这个问题的一种快速方法是简单地使用一些jQuery.它只需要两行代码即可实现.
var imgWidth = $('.image').width();
$('.content').width(imgWidth);

大佬总结

以上是大佬教程为你收集整理的html – 将元素的宽度设置为兄弟的宽度全部内容,希望文章能够帮你解决html – 将元素的宽度设置为兄弟的宽度所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。