Centering a Horizontal
Problem:
A horizontal menu consisting of an unordered list (
) needs to be centered within a container <div>. While attempts to center the within the <div> have been successful, the individual list items (- ) remain left-aligned within the
.
Solution:
To achieve perfect centering of both the
and its list items, the following approach is recommended:
-
Float Wrapper: Create a float-left wrapper around the
and set its position to "relative" with a negative left offset. This positions the wrapper off-screen to the left.
-
Reverse Nested Element: Position the inner
within the wrapper using "position: relative" and a positive left offset of 50%. This places the exactly at the center of the wrapper.
-
Float List Items: Adjust the
- elements to float left within the
and maintain their position within the using "position: relative."
Code Example:
#buttons {
float: right;
position: relative;
left: -50%;
text-align: left;
}
#buttons ul {
list-style: none;
position: relative;
left: 50%;
}
#buttons li {
float: left;
position: relative;
}
Copy after login
HTML Example:
With this implementation, the menu will be perfectly centered, with the list items evenly distributed within the horizontal space.
The above is the detailed content of How to Perfectly Center a Horizontal `` Menu and its List Items?. For more information, please follow other related articles on the PHP Chinese website!