This time I will introduce frequently used how to center elements with css.
This code is for inline elements such as text and images. Set text-align: center; on the parent element.
center1 {
text-align: center;
}
<div class="center1">YourIllust</div>
This automatically creates margin outside the element and center it. This has to be set “width”. If you want to make responsive design, use “%”.
.center2 {
margin: 0 auto;
width: 100px;
height: 100px;
background-color: #93d1ee;
}
<div class="center2"></div>
justify-content is a property that specifies the placement of elements aligned horizontally with display: flex;.
.center3 {
display: flex;
justify-content: center;
}
.center3-child1, .center3-child2, .center3-child3 {
width: 100px;
height: 100px;
}
.center3-child1 {
background-color: #93d1ee;
}
.center3-child2 {
background-color: #343333;
}
.center3-child3 {
background-color: #f0f2f4;
}
<div class="center3">
<div class="center3-child1"></div>
<div class="center3-child2"></div>
<div class="center3-child3"></div>
</div>
align-items property is used to set vertical position. justify-content property is used to set the horizontal position. This code centers child elements inside target elements vertically and horizontally.
.center4 {
display: flex;
align-items: center;
justify-content: center;
width: 200px;
height: 200px;
background-color: #93d1ee;
}
<div class="center4">YourIllust</div>
align-items property is used to set vertical position. justify-content property is used to set the horizontal position. This code centers target elements inside parent elements vertically and horizontally.
.center5 {
position: relative;
height: 300px;
margin-top: -22px;
}
.center5-child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: #93d1ee;
width: 200px;
height: 200px;
}
<div class="center5">
<div class="center5-child">YourIllust</div>
</div>
I introduced 5 ways to center elements with CSS. Each has a different function, so use the right code in the right place.