When centering horizontally, li's get cut off
How can I center the ul without having it get cut off?
That was a really good question, had some trouble figuring a way to achieve this behavior.
I don't believe you will find a pure CSS
solution, however we can do it using a bit of javascript
.
Basically i´ve created a script attached to the window resize event that will do the following:
- check how many items we have inside our wrapper element:
#wrapper
- divide the number of elements by 3 (since we have 3 elements in each column) to discover how many columns will be needed to display the items
- assign a width to the wrapper element using the following formula: number of columns * width of each item (in our case that's
200px
)
Doing that we force the overflow in the parent element, and the scrollbar will have a normal behavior, showing every element.
The full code is available in jsfiddle
.
Check the following example:
function onResize() {
var wrapper = document.querySelector('#wrapper');
var items = wrapper.querySelectorAll('li');
var columns = Math.ceil(items.length / 3);
var width = 200 * columns;
wrapper.style.width = width > window.innerWidth ? width + 'px' : '100%';
}
onResize();
window.addEventListener('resize', onResize);
html,
body {
height: 100%;
text-align: center;
}
*,
*:before,
*:after {
box-sizing: border-box;
padding: 0;
margin: 0;
}
#wrapper {
height: 100%;
display: inline-flex;
align-items: center;
justify-content: center;
background-color: aqua;
}
ul {
height: 75%;
list-style: none;
display: flex;
align-content: center;
flex-direction: column;
flex-wrap: wrap;
}
li {
flex-basis: calc(100% / 3 - 2px);
color: firebrick;
border: 1px solid firebrick;
background-color: greenYellow;
width: 200px;
display: flex;
align-items: center;
justify-content: center;
}
<div id="wrapper">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
</div>