Expand the inner width of the div while scrolling the parent element horizontally

I have a sidebar with some listings. Each list is preceded by a title bar div. The side panel has a fixed width and overflow-x: auto. The content list may overflow, making the parent sidebar to display the scroll bar.

The problem is that the title bar divdoes not expand when the scrollbar appears. I would also like to not move it when scrolling or expand the "div" to fit the extra space created by the scroll bar: JS Bin

Is it possible to solve this problem with CSS?

+4
source share
2 answers

This may be possible with CSS, but in my opinion, you will need to use some JavaScript to fix this problem:

Here is the trick:

var sidebar = $('.sidebar');

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

We will add some margin-leftto the elements .titleequal to the number of horizontal scroll pixels. This will always show the title bar to the right of the scrollable item.

$(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>
Run code
+2
source

Please find the solution below with CSS only.

.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>
Run code
+1
source

Source: https://habr.com/ru/post/1677995/


All Articles