Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering a percent-based div

Tags:

html

css

Recently, a client asked that his site be percent-based rather than pixel-based. The percent was to be set to 80%. As you guys know, it is very easy to center the container if it is pixel-based but how do you center a percent-based main container?

#container {   width:80%;   margin:0px auto; } 

That does not center the container :(

like image 936
Sarfraz Avatar asked Apr 12 '10 17:04

Sarfraz


People also ask

How do I center a specific div?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.

How do I center a div with margin?

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 I center a div according to my screen size?

Easiest way to center something regardless of page width is margin: auto; in your CSS, with height and width defined. Save this answer.

How do I center a floating div?

You can set float div center by using margin property. you does not need to use float property but you can use margin property and set left or right margin value auto by this way.


2 Answers

The margin property supports percentage values:

margin-left: 10%; margin-right: 10%; 
like image 93
David Avatar answered Sep 18 '22 05:09

David


#container {   width:80%;   position:absolute;   margin-left:-40%;   left:50%; } 

or simply

#container {   width:80%;   margin-left:10%; } 
like image 39
oezi Avatar answered Sep 19 '22 05:09

oezi