让孩子接受父母溢出的宽度

时间:2019-12-08 19:24:02

标签: html css

我在显式宽度父级中有许多子项,例如

document.querySelector('.parent').scrollTo(100,0)
.parent {
  overflow: auto;
  width: 200px;
}
.child {
  font-size: 40px;
  background-color: blue;
  white-space: nowrap;
}
<div class='parent'>
  <div class='child'>asdf asdf adsf asdf</div>
  <div class='child'>asdf</div>
  <div class='child'>asdf</div>
  <div class='child'>asdf</div>
  <div class='child'>asdf</div>
  <div class='child'>asdf</div>
</div>

我希望child项背景能够覆盖整个子级。但是,该范围不会超出初始可见区域。您可以在下面的图像中看到我的意思,在该图像中水平滚动了父级:

enter image description here

4 个答案:

答案 0 :(得分:0)

尝试在.child元素上添加display: inline-block;

答案 1 :(得分:0)

更改此内容:

  .parent {
      overflow: auto;
      width: 200px;
      background-color: blue;
    }

检查:https://jsfiddle.net/sugandhnikhil/pLbfatgc/

答案 2 :(得分:0)

我认为仅凭CSS不可能做到这一点。背景将占据元素宽度的100%,在这种情况下为200px,而不是滚动宽度。

有一些技巧可以使用javascript完成工作。您可以获取父级的scrollWidth,然后将其设置为每个子级的宽度。强制每个孩子长到孩子最长的宽度。

但是,这不是响应式的解决方案。如果您为不同的屏幕尺寸调整文本或父级的大小,则需要重新计算子级的宽度。

document.querySelector('.parent').scrollTo(100,0);
var scrollWidth = document.querySelector('.parent').scrollWidth;
var children = document.querySelectorAll('.parent .child');
for (var i = 0; i < children.length; i++) {
    children[i].style.width = scrollWidth + "px";
}
.parent {
  overflow: auto;
  width: 200px;
}
.child {
  font-size: 40px;
  background-color: blue;
  white-space: nowrap;
}
<div class='parent'>
  <div class='child'>asdf asdf adsf asdf</div>
  <div class='child'>asdf</div>
  <div class='child'>asdf</div>
  <div class='child'>asdf</div>
  <div class='child'>asdf</div>
  <div class='child'>asdf</div>
</div>

答案 3 :(得分:0)

您可以使用box-shadow

对其进行破解

document.querySelector('.parent').scrollTo(100,0)
.parent {
  overflow: auto;
  width: 200px;
}
.child {
  font-size: 40px;
  background-color: blue;
  box-shadow: 200px 0 0 blue;
  white-space: nowrap;
}
<div class='parent'>
  <div class='child'>asdf asdf adsf asdf</div>
  <div class='child'>asdf</div>
  <div class='child'>asdf</div>
  <div class='child'>asdf</div>
  <div class='child'>asdf</div>
  <div class='child'>asdf</div>
</div>

相关问题