How to horizontally center a floating element of a variable width?
Edit: I already have this working using a containing div
for the floating element and specifying a width
for the container (then use margin: 0 auto;
for the container). I just wanted to know whether it can be done without using a containing element or at least without having to specify a width
for the containing element.
Center Align Elements To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
The CSS float property is used to set or return the horizontal alignment of elements. But this property allows an element to float only right or left side of the parent body with rest of the elements wrapped around it. There is no way to float center in CSS layout.
To center a div horizontally on a page, simply set the width of the element and the margin property to auto. That way, the div will take up whatever width is specified in the CSS and the browser will ensure the remaining space is split equally between the two margins.
Like last time, you must know the width and height of the element you want to center. Set the position property of the parent element to relative . Then set the child's position property to absolute , top to 50% , and left to 50% . This just centers the top left corner of the child element vertically and horizontally.
Assuming the element which is floated and will be centered is a div
with an id="content"
...
<body> <div id="wrap"> <div id="content"> This will be centered </div> </div> </body>
And apply the following CSS:
#wrap { float: left; position: relative; left: 50%; } #content { float: left; position: relative; left: -50%; }
Here is a good reference regarding that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With