I use css style text-align to align contents inside a container in HTML. This works fine while the content is text or the browser is IE. But otherwise it does not work.
Below are the methods which have always worked for me
Set the display of the parent div to display: flex;
and the you can align the child elements inside the div using the justify-content: center;
(to align the items on main axis) and align-items: center;
(to align the items on cross axis).
If you have more than one child element and want to control the way they are arranged (column/rows), then you can also add flex-direction
property.
Working example:
.parent {
align-items: center;
border: 1px solid black;
display: flex;
justify-content: center;
height: 250px;
width: 250px;
}
.child {
border: 1px solid black;
height: 50px;
width: 50px;
}
2. (older method) Using position, margin properties and fixed size
Working example:
.parent {
border: 1px solid black;
height: 250px;
position: relative;
width: 250px;
}
.child {
border: 1px solid black;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 50px;
position: absolute;
width: 50px;
}