How to Horizontally Center a <div> in Another <div>
The <div> tag is used to define parts of a page or a document. Learn How to Horizontally Center a <div> in Another <div> with W3docs tutorial.
The HTML <div> tag is used to define parts of a page or a document. It groups large sections of HTML elements and styles them with CSS.
If you want to put a <div> element in the center of another <div>, use CSS styles to position it exactly at the center of another <div> horizontally. Follow the steps below and get the code snippet.
Create HTML
- Create two
<div>elements with<span class="attribute">id</span>attributes named "outer-div" and "inner-div". Place the second<div>within the first one.
How to create HTML <div> elements with IDs "outer-div" and "inner-div"
<div id="outer-div">
<div id="inner-div">I am a horizontally centered div.</div>
</div>Add CSS
- Set the width of the outer element (i.e. 100% covers the whole line). Change it according to your requirements.
- Set a width for the inner
<div>(e.g., 200px). The "margin: 0 auto" property only centers block-level elements with a specified width. - Set the display property to "block" to make the inner
<div>a block-level element. - Set the margin property to "auto" to horizontally center the
<div>element within the outer<div>. The "margin: 0 auto" does the actual centering. - Set your preferred colors for the outer and inner
<div>elements by using the background-color property.
how to style an HTML element using CSS width, margin, background-color, display, text-align and padding properties ?
#outer-div {
width: 100%;
text-align: center;
background-color: #0666a3
}
#inner-div {
display: block;
width: 200px;
margin: 0 auto;
padding: 3px;
background-color: #8ebf42
}Here is the full code.
Example of horizontally centering a <div> element within another one using margin and display properties:
An example of how to horizontally center a <div> in another <div> tag
<!DOCTYPE html>
<html>
<head>
<style>
#outer-div {
width: 100%;
text-align: center;
background-color: #0666a3
}
#inner-div {
display: block;
width: 200px;
margin: 0 auto;
padding: 3px;
background-color: #8ebf42
}
</style>
</head>
<body>
<div id="outer-div">
<div id="inner-div"> I am a horizontally centered div.</div>
</div>
</body>
</html>Result
<div class="demo px-2.5 mt-1 mb-5 not-prose"> XFI4 <div id="inner-div"> I am a horizontally centered div. </div> </div> </div>
Set also padding to create space around the inner element.
Example of horizontally centering a <div> element within another one with the display property:
Example of a horizontally centered div with the CSS display property:
<!DOCTYPE html>
<html>
<head>
<style>
#main-container {
display: flex;
width: 100%;
justify-content: center;
background-color: #0666a3;
}
#main-container div {
background-color: #8ebf42;
padding: 10px;
}
</style>
</head>
<body>
<div id="main-container">
<div> I am a horizontally centered div with the CSS display property.</div>
</div>
</body>
</html>