水平滚动 parent 时展开内部 div 宽度

Expand inner div width when horizontally scrolling parent

我有一个带有一些列表的边栏。每个列表前面都有一个标题栏 div。侧边栏具有固定宽度和 overflow-x: auto。列表内容可以溢出,使 parent 侧边栏显示滚动条。

问题是当滚动条出现时标题栏 div 没有展开。我想要,滚动时不要移动它或展开 'div' 以适应滚动条生成的额外 space:JS Bin

是否可以使用 CSS 解决此问题?

使用 CSS 可能是可行的,但在我看来,您需要使用一些 JavaScript 来解决此问题:

技巧如下:

var sidebar = $('.sidebar');

sidebar.scroll(function(e) {
  sidebar.find('.title').css({
    marginLeft: sidebar.scrollLeft()
  });
});

我们将在 .title 元素上添加一些 margin-left 等于水平滚动的像素数。这将始终在可滚动元素的右侧显示标题栏。

$(function() {
  var sidebar = $('.sidebar');
  
  sidebar.scroll(function(e) {
    sidebar.find('.title').css({
      marginLeft: sidebar.scrollLeft()
    });
  });
});
.sidebar {
  overflow-x: auto;
  width: 160px;
  height: 195px;
  background-color: lightgrey;
  padding-top: 20px;
}

.title {
  width: 100%;  
  text-align: right;
  background-color: grey;
}

.list {
  margin-top: 20px;
  white-space: nowrap;
} 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar">
  <div class="title">
    Title
  </div>
  <ul class="list">
    <li>
      This is a very long long line
    </li>
  </ul>
  <div class="title">
    Title2
  </div>
  <ul class="list">
    <li>
      This is a very long long line
    </li>
  </ul>
</div>

请仅使用 CSS 找到下面的解决方案。

.sidebar {
  overflow-x: auto;
  width: 160px;
  height: 200px;
  background-color: lightgrey;
  padding-top: 20px;
  overflow-x: scroll;
}

.title {
  width: 160px;
  text-align: right;
  position: fixed;
  background-color: grey;
}

.list {
  margin-top: 30px;
  white-space: nowrap;
  float: left;
}

.clear {
  clear: both;
}
<title>
  JS Bin
</title>

<body>
  <div class="sidebar">
    <div class="title">
      Title
    </div>
    <ul class="list">
      <li>
        This is a very long long line
      </li>
    </ul>
    <div class="clear">
      <div class="title">
        Title2
      </div>
      <ul class="list">
        <li>
          This is a very long long line
        </li>
      </ul>
      <div class="clear">
      </div>
</body>