➢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 element will then take up the specified width, and the remaining space will be split equally between the two margins:
EXAMPLE:
div { margin: auto;
width: 50%;
border: 3px solid green;
padding: 10px;
}
RESULT:
The div element is centered
➢To just center the text inside an element, use text-align: center;
EXAMPLE:
div { margin: auto;
width: 50%;
border: 3px solid green;
padding: 10px;
text-align: center;
}
RESULT:
➢There are many ways to center an element vertically in CSS. A simple solution is to use top and bottom padding :
EXAMPLE:
div {
border: 3px solid green;
padding: 70px;
}
RESULT:
I am vertically centered.
➢Another trick is to use the line-height property with a value that is equal to the height property:
EXAMPLE:
div {
line-height: 200px;
height: 200px;
border: 3px solid green;
text-align: center;
}
div p {
line-height: 1.5;
display: inline-block;
vertical-align: middle;
}
RESULT:
I am vertically and horizontally centered.
➢If padding and line-height are not options, another solution is to use positioning and the transform property:
EXAMPLE:
div {
height: 200px;
border: 3px solid green;
position: relative;
}
div p {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
RESULT:
I am vertically and horizontally centered.
BMR EDUCATION
BMR EDUCATION is provided for learning and imparting knowledge in all aspects. Concepts may be simplified to enhance readability and learning. The content we provide is regularly reviewed to minimize errors, but we cannot guarantee the absolute correctness of all content. When using the BMR Education website, you agree to have read and accepted the Terms and Conditions , and Privacy Policy .
BMR EDUCATION © 2024 All rights reserved