techtext ipoint

(3) Ways of centering elements in CSS

General context

When it comes to centering things in CSS there are some ways of doing that. Here a few interesting techniques are presented that are used to center things both horizontally and vertically:

(a) Technique with the usage of negative margins
(b) Technique with the usage of calc() CSS function
(c) Technique with the usage of transform: translate() property
(d) Technique with the usage of Flexbox justify-content and align-items properties

Main assumptions

(a) There are two elements: div tag with the class ”container” - the parent one and div tag with the class ”element” - the child one that will be centered inside a container
(b) container has width: 100vw and height: 100vh
.container {
width: 100vw;
height: 100vh;
}

Technique with the usage of negative margins

.element {
width: 50vw;
height: 50vw;
position: absolute;
top: 50%;
left: 50%;
margin-top: -25vw;
margin-left: -25vw;
background-color: orange;
}


We also add to parent container position: relative property:
.container {
width: 100vw;
height: 100vh;
position: relative;
}

Technique with the usage of calc() CSS function

.element {
width: 80vh;
height: 45vh;
position: absolute;
top: calc(50% - 45vh/2);
left: calc(50% - 80vh/2);
background-color: orange;
}


We also add to parent container position: relative property:
.container {
width: 100vw;
height: 100vh;
position: relative;
}

Technique with the usage of transform: translate() property

Version with top and left properties:
.element {
width: 30vw;
height: 30vh;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: orange;
}


Version with bottom and right properties:
.element {
width: 30vw;
height: 30vh;
position: absolute;
bottom: 50%;
right: 50%;
transform: translate(50%, 50%);
background-color: orange;
}


We also add to parent container position: relative property:
.container {
width: 100vw;
height: 100vh;
position: relative;
}

Technique with the usage of Flexbox justify-content and align-items properties

.element {
width: 30vw;
height: 30vh;
background-color: orange;
}


We also add to parent container display: flex property and justify-content: center and align-items: center properties
.container {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}