Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to horizontally center a floating element of a variable width?

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.

like image 981
Waleed Eissa Avatar asked Aug 05 '09 09:08

Waleed Eissa


People also ask

How do you center an element horizontally?

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.

How do you center a floating element?

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.

How do I make a div centered horizontally?

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.

How do you center an element?

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.


1 Answers

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.

like image 194
Leyu Avatar answered Sep 30 '22 18:09

Leyu