In this question, I am not going to ask “How” to horizontally center an unordered list, because there are about eleventy thousand resources already on the internet for that.
Instead, I’d liked to ask the “WHY” part of it.
More precisely, why do we do this
ul {
position:relative;
left:50%;
}
ul > li {
position:relative;
right: 50%;
}
instead of this:
ul {
position:relative;
left:25%;
}
When both seem to do the trick.
Any thoughts?
The reason is, because the first method centers the
ulin every case – indepentend on how many childliit has.The second solution places the
ul25% to the right which will work in a very special case, when the widht of theliis just right to occupy 50% of the total width but breaks in any other case.using
lefton the parent andrighton the child is a very common practice to center a child with dynamic dimensions(width) which is the case when dealing with dynamic content.In some cases,
text-align:center;works too, but fails when you have to use absolute positioning.See an example fiddle here.