0

Have a div element fixed to the side of my webpage with a bunch of years in it. It has overflow-y: hidden for default and then, on :hover, overflow-y: auto.

When I mouse over the element, all the content bumps to the left 17px (width of scrollbar) because of it being centered.

I've looked for a solution and found this on The Stack, but the solutions only apply to problems involving the entire window.

CSS posted below, the relevant HTML only has the DIV container and .year elements but if you want it I can throw it up here as well. Pic comparison isn't centered properly but still shows the issue.

enter image description here

.sideBar {
  background-color: #ff9900;
  height: 150px;
  width: 200px;
  overflow-y: hidden;
}
.sideBar:hover {
  overflow-y: auto;
}
.year, .h2year {
  text-align: center;
  margin: 1em 0;
}
.year:hover {
  font-weight: bold;
}
<div class="sideBar" id="yearsBar">
  <div>
    <h2 class="h2year">Years</h2>
    <p class="year" id="2015">2015</p>
    <p class="year" id="2014">2014</p>
    <p class="year" id="2013">2013</p>
    <p class="year" id="2012">2012</p>
    <p class="year" id="2011">2011</p>
    <p class="year" id="2010">2010</p>
  </div>
</div>
Community
  • 1
  • 1
Kevin
  • 302
  • 2
  • 11

1 Answers1

2

You can use an inner wrapper (you already had a div). Then,

  • Set the desired height to the outer wrapper and the desired width to the inner one.
  • Display the outer wrapper as an inline-block, in order to make it shrink to the size of its content.
  • Hide the overflow on the outer wrapper. Use overflow-y: scroll at :hover.
#outer-wrapper {
  height: 150px;
  overflow: hidden;
  display: inline-block;
}
#outer-wrapper:hover {
  overflow-y: scroll;
}
#inner-wrapperv {
  width: 200px;
}

.sideBar {
  background-color: #ff9900;
  height: 150px;
  overflow: hidden;
  display: inline-block;
}
.sideBar:hover {
  overflow-y: scroll;
}
.sideBar > div {
  width: 200px;
}
.year, .h2year {
  text-align: center;
  margin: 1em 0;
}
.year:hover {
  font-weight: bold;
}
<div class="sideBar" id="yearsBar">
  <div>
    <h2 class="h2year">Years</h2>
    <p class="year" id="2015">2015</p>
    <p class="year" id="2014">2014</p>
    <p class="year" id="2013">2013</p>
    <p class="year" id="2012">2012</p>
    <p class="year" id="2011">2011</p>
    <p class="year" id="2010">2010</p>
  </div>
</div>

At least, it works on Firefox, Chrome and IE8.

Oriol
  • 274,082
  • 63
  • 437
  • 513