This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
Last week I shared a #devsheet covering the CSS width properties min-content
, max-content
, and fit-content
. I recommend having a look if you're not familiar with these CSS properties.
While reading about these underused properties, I discovered a neat pattern to build a centered navigation bar on CSS-Tricks.
The pattern uses fit-content
to make the navigation take the exact amount of space to fit in all entries. The list container is then moved into the horizontal center using margin: 1em auto;
.
ul {
background: deepskyblue;
padding: 1em;
/* try to give the list as much space as needed */
width: -webkit-fit-content;
width: -moz-fit-content;
width: fit-content;
/* move the container to the center on the X-axis */
margin: 1em auto;
}
li {
display: inline-block;
background: tomato;
padding: .5em;
}
If you tried to give a centered navigation bar the exact fitting width paired with a background or border color, you might have already lost some hair on this problem.
Using fit-content
is a beautiful solution, and I'm sure I'll reuse this pattern repeatedly in the future!
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
Stefan Judis | Sciencx (2020-11-21T23:00:00+00:00) A centered CSS navigation with fit-content (#snippet). Retrieved from https://www.scien.cx/2020/11/21/a-centered-css-navigation-with-fit-content-snippet/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.