How block elements can be centered using CSS ?
In this article, we will see how to make block-level elements to the center using CSS.
Approach: There are two steps to center a block-level element –
Step 1: Define the external width – We need to define the external width. Block-level elements have the default width of 100% of the webpage, so for centering the block element, we need space around it. So for generating the space, we are giving it a width.
Step 2: Set the left-margin and the right-margin of the element to auto – Since we produced a remaining space by providing external width so now we need to align that space properly that’s why we should use margin property. Margin is a property that tells how to align a remaining space. So for centering the element you must set left-margin to auto and right-margin to auto.
Syntax:
element {
width:200px;
margin: auto;
}
The below examples represent how to center block-level elements.
Example 1: Here a single element (div) is centered inside the body.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< style >
*{
margin:0px;
padding:0px;
box-sizing: border-box;
}
body {
background: brown;
}
#box {
background: black;
color:white;
text-align: center;
}
/* For centering the element */
#box {
width:300px;
margin:10rem auto;
}
</ style >
</ head >
< body >
< div id = "box" >
< h3 >this is a box</ h3 >
</ div >
</ body >
</ html >
|
Output:
Example 2: Here we have centered two elements one after another by giving external height and width.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< style >
*{
margin:0px;
padding:0px;
box-sizing: border-box;
}
body {
background: cadetblue;
}
.box {
background: rgb(4, 2, 32);
color: #eee;
text-align: center;
width: 500px;
height: 200px;
margin:1rem auto;
}
</ style >
</ head >
< body >
< div id = "box1" class = "box" >
< h3 >this is a box1</ h3 >
</ div >
< div id = "box1" class = "box" >
< h3 >this is a box2</ h3 >
</ div >
</ body >
</ html >
|
Output:
Last Updated :
22 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...