To horizontally center an element using CSS, you can use the margin
property with the auto
value.
Here’s an example of how you can horizontally center a div
element with a fixed width:
div { width: 200px; margin: 0 auto; }
This will center the div
element horizontally within its parent element.
You can also use the text-align
property to center inline elements, like this:
p { text-align: center; }
This will center all of the inline content within the p
element horizontally.
Keep in mind that these methods only work if the element has a fixed width, or if the parent element has a fixed width. If the element or its parent has a flexible width (e.g., width: 100%
), the element will stretch to fill the available space.