How to make a div center align in HTML
<!DOCTYPE html><html> <head> <title>Center</title> </head> <body>
<div style="text-align: center;"> <div style="width: 500px; margin: 0 auto; background: #000; color: #fff;">This DIV is centered</div> </div>
</body></html>
How to align a div to the middle (horizontally/width) of the page
<body>
<div style="width:800px; margin:0 auto;">
centered content
</div>
</body>
How can I horizontally center an element?
You can apply this CSS to the inner <div>
:
#inner {
width: 50%;
margin: 0 auto;
}
Of course, you don't have to set the width
to 50%
. Any width less than the containing <div>
will work. The margin: 0 auto
is what does the actual centering.
If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:
#inner {
display: table;
margin: 0 auto;
}
It will make the inner element center horizontally and it works without setting a specific width
.
Working example here:
#inner {
display: table;
margin: 0 auto;
border: 1px solid black;
}
#outer {
border: 1px solid red;
width:100%
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
How can I center a div within another div?
You need to set the width
of the container (auto
won't work):
#container {
width: 640px; /* Can be in percentage also. */
height: auto;
margin: 0 auto;
padding: 10px;
position: relative;
}
The CSS reference by MDN explains it all.
Check out these links:
- auto - CSS reference | MDN
- margin - CSS reference | MDN
- What is the meaning of
auto
value in a CSS property - Stack Overflow
In action at jsFiddle.
Center a DIV horizontally and vertically
After trying a lot of things I find a way that works. I share it here if it is useful to anyone. You can see it here working: http://jsbin.com/iquviq/30/edit
.content {
width: 200px;
height: 600px;
background-color: blue;
position: absolute; /*Can also be `fixed`*/
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
/*Solves a problem in which the content is being cut when the div is smaller than its' wrapper:*/
max-width: 100%;
max-height: 100%;
overflow: auto;
}
Related Topics
How to Have Scrollbar When Position Is Negative
CSS - Background Images Not Displaying Properly on Mobile Browsers
Can CSS: Not Selector Target: Before and: After Selectors
Cant Edit CSS Style Properties (Grayed Out & Blocked) in Chrome
Django 1.8 Static Files Doesnt Work
Showing The Jsf Error Messages
Using Rems with a Pixel Fallback
CSS Animation Keyframes with Display None Works to Fade In, But Not Fade Out
Styles Based on Number of Children
How to Include "Leaflet.CSS" in a React App with Webpack
Vertically Center a Div with Variable Height Within a Div That Is 100% of The Viewport
Google Fonts External CSS Vs Copying The Code of External CSS in My CSS
Why Does Chrome Read The Svg Circle Radius from The Style Attribute
Complex Selector Don't Work in Last Blink Version: Nth-Child(2):Nth-Last-Child(2){}