Mike Mike - 3 months ago 7
CSS Question

How do I get a scroll bar to appear on my DIV while at the same time centering it on my screen?

I’m styling an unordered list, the structure of which is

<div class="select-styled active">Arizona</div><ul class="select-options" style="display: block;"><li rel="">Select State</li><li rel="3526">Alabama</li><li rel="3556">Alaska</li><li rel="3547">Arizona</li><li rel="3510">Arkansas</li><li rel="3542">California</li>…<li rel="3554">Wyoming</li></ul></div>


There are usually more options than there’s room on the screen to display, which is fine — usually there’s a way to scroll. However, when I add a div container to center everything …

<div id="profileContainer">
<div class="profileField address">
<div class="select-styled active">Arizona</div><ul class="select-options" style="display: block;"><li rel="">Select State</li><li rel="3526">Alabama</li><li rel="3556">Alaska</li><li rel="3547">Arizona</li><li rel="3510">Arkansas</li><li rel="3542">California</li>…<li rel="3554">Wyoming</li></ul></div>
</div>
</div>


with this style

#profileContainer {
border-radius: 25px;
background: #ffffff;
padding: 10px;
width: 100%;
max-width: 720px;
display: inline-block;
position: fixed;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}


But now there’s no way to scroll. Here's my JSFiddle -- https://jsfiddle.net/d2r50gc1/. How can I center my items in the center of the screen and also have a scroll bar on the unordered list so that I can see all the items?

Answer

I think I've accomplished what you want: https://jsfiddle.net/d2r50gc1/11/

All you need to do is apply a few styles to the unordered list:

ul.select-options {
    max-height: 15em;
    overflow-y: scroll;
    overflow-x: hidden;
}

By using em (or rem) units instead of px you retain support for users who choose to alter their font size which I noted you expressed interest in on another answer's comments. You can alter that 15em which is an arbitrarily chosen multiplier to any number as you see fit. You might also consider using rem instead of em but you'll have to make that decision on your own dependent on your final desired use case. If you change the padding definition to also use em or rem you can use math to set the size to always show a certain number of elements in the drop down.

Comments