Introduction
Prerequisites
The Box Model
How to Center a Div in CSS
How to Center a Div Horizontally
How to Center a Div Vertically
Centering both Horizontally and Vertically
Comparing the Techniques
Conclusion
Introduction
The difficulty of centering divs has to be one of the most "memeable" topics in programming. Fear not, however, gone are the days of IE5, CSS isn't tables and floats anymore, today with techniques using innovations like Flexbox, or even CSS Grid, centering DIVs has never been easier.
Div, short for content division element, defines a division in an HTML document. It is a generic block-level element that serves as a container for HTML elements, which can then be styled and manipulated with CSS and Javascript.
So, how the heck do you center a div?
In this article, I'll take you through the different techniques used in centering divs, from horizontal centering to vertical, centering texts, and even centering both ways simultaneously.
Prerequisites
Preliminary knowledge of HTML
Basic CSS knowledge
The Box Model
Before I get into centering techniques, I must first make sure you understand the CSS box model.
Every HTML element is its own box, with its spacing and border, this is called the box model. It contains four properties, margin, border, padding and your content, which can then be styled or manipulated however you see fit.
The margin property creates a margin around your selected content, and the padding property, which is a close relative of the margin creates spaces inside the edges of your div container. This means that it adds spaces between the content and the edges of the container.
Therefore, whereas margin creates space on the outside, padding creates space on the inside of your selected element.
Finally, the border property controls the border between the margin and the padding.
What you should remember is this:
Margin (Spacing on the outside)
Border (The in-between)
Padding (Spacing on the inside)
Content (The content itself)
How to Center a Div in CSS
Understanding how to center divs and text within divs is a valuable skill for beginners and seasoned developers alike.
To create visually stunning layouts, knowing how to center divs will help in arranging and styling elements on your page.
Although I mentioned earlier that centering divs today has never been easier, I must admit that this task might prove surprisingly intricate and confusing due to the nuances of CSS and the various scenarios in which centering may be required.
In this guide, I'll cover the various methods to center a div depending on the specific requirement of your project, and the context of your design.
How to Center a Div Horizontally
To center a div horizontally on a page, you can try the following:
1.Margin: auto
Here you can leverage the margin:auto;
property by setting the left/right margins to auto. When centering elements horizontally using the margin property, three things must be considered:
(A). Display should be set to block: This allows for no other elements besides the current one. It takes ownership of the horizontal space of the element. However, since divs are block-level elements, this step can be omitted if your content is within a div.
(B). Must have a width: An item cannot be centered within a browser if it is wider than the browser itself. Therefore, your element must have a set width.
(C). Margin left/right set to auto: 'Auto' means 'take up all the space', and since this is a display: block;
element, the space would be what's left after your content has taken up the required pixels in width. The margin left/right being set to auto centers the div since they are being pushed against each other.
You can also use the shorthand margin
property with the value 0 auto
to center divs.
<div class="center">
<img src="cat.jpg" alt="cat sleeping on rug">
</div>
<!--This is a simple code snippet showing an image of cat contained
within a div element-->
<!--This div can now be styled using css -->
To center the cat image in CSS, you'll code:
.center {
width: 50%;
margin: 0 auto;
}
/*Here, display:block; isn't used because the div is already a
block-level element*/
Setting the margin-top to 0, and the horizontal margin to auto using the shorthand property removes the margin-top and horizontally centers the image. Therefore, the output will be:
2.Flexbox centering
Introduced in CSS3, Flexbox has revolutionized how we design layouts by providing a better way to arrange, align, and distribute space among items within a container.
It is the most modern method to center elements on a page. To ensure that Flexbox creates the appropriate row/column you want, wrap your desired row/column in a <div>
element.
A Flexbox layout always contains a container and its direct children. To use Flexbox, you need to give an element a 'display' property of 'flex'. This will make the element a 'flex container', and any direct children of a flex container are called 'flex items'.
To begin create a div
and give it a class of container, using the above cat example create an img
element with src
and alt
attributes.
<div class="container">
<img src="cat.jpg" alt="cat sleeping on rug">
</div>
.container{
display: flex;
justify-content: center;
}
/* justify-content set to center centers the cat image */
Output:
At its core, Flexbox takes every single item and turns it into a row or column depending on its flex-direction
. Note that Flexbox only turns into rows/columns "direct children" elements.
3.Text Align set to Center
To center texts properly, use the text-align
property in CSS and give it a value of center
.
<div class="center-text">
Centered Text
</div>
.center-text {
text-align: center;
background-color: lightblue;
padding: 20px;
}
The output looks like this, you can see the words 'centered text' have been effectively centered on our page.
4.CSS Grid
This is a layout grid system in CSS that allows us to create web layouts easily. Using CSS Grid you can define a grid structure and place items within the grid. This gives us total control over the alignment and positioning of our elements.
Although CSS Grid is primarily used for grid-based designs, it can also be used to center elements easily.
<div class="container">
<div class="center-grid">Grid Layout Horizontal Centering.</div>
</div>
.container {
display: grid;
place-items: center; /* centers the child horizontally */
background-color: pink;
height: 100vh; /* just for this example */
}
.center-grid {
background-color: lightseagreen;
width: 50%;
text-align: center;
Output:
How to Center a Div Vertically
To center a div vertically on a page, you can try the following:
1.Using CSS Position and Transform Properties
The position property in CSS specifies the kind of positioning method used for an element on your page. It changes an element's position in your document flow, which can affect the layout of other elements on your page.
On the other hand, CSS translate is a transform function that can move an element without affecting the layout of other elements on your page.
Combining these two properties can help you center a div. The position property will affect the element's position on your page while the translate function will move the element from that particular position.
In this case, we're going to set our position
property to relative
. An element with position: relative;
is positioned relative to its normal/default position. Then shift the element 50% from the top and 50% from the left to align it at the center. Now add the transform
property and set it to translate
with the value -50% to effectively center it.
<div class="container">
<div class="position-transform">
Vertical Centering
</div>
</div>
.container{
position: relative;
height: 100vh;
background-color: black;
}
.position-transform {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: pink;
}
The output looks like this:
2.CSS Grid
CSS Grid can also be used for vertical centering. All you need to do is give your element a display
of grid
, then align the item to the center.
<div class="container">
<div class="vertical-grid">
Vertical Centering
</div>
</div>
.container{
display: grid;
align-items: center;
background-color: coral;
height: 100vh;
}
.vertical-grid {
background-color: lightseagreen;
width: 100%;
}
Output:
3.Flexbox centering
As I mentioned above, Flexbox is a one-dimensional CSS layout that controls how items are aligned or spaced within a container. This means you can also center elements vertically using Flexbox.
To begin create a container div and an additional div nested inside setting its class to 'vertical-flex'. Then in CSS, give your element a display
of flex
and align it to the center.
.container{
display: flex;
align-items: center;
background-color: grey;
height: 100vh;
}
.vertical-flex {
background-color: lightcoral;
width: 50%;
}
Output:
Centering both Horizontally and Vertically
1.CSS Grid
To center an element both ways using CSS Grid, establish grid by giving your container a display property of grid, then place your content to the center by using the place-item
property.
.container{
display: grid;
place-items: center;
background-color: lightgray;
height: 100vh;
}
/* place-item centers your content both ways while
align-item only vertically centers your content*/
.horizontal-vertical-grid {
text-align: center;
background-color: rgb(127,255,127);
width: 50%;
}
Output:
2.Flexbox
Flexbox is versatile and can also handle both horizontal and vertical centering easily. Establish Flexbox by giving your container element a display
of flex
, justify your content by setting it to center, and align your content to the center to vertically center it.
.container{
display: flex;
justify-content: center;
align-items: center;
background-color: grey;
height: 100vh;
}
.horizontal-vertical-flex {
text-align: center;
background-color: orange;
width: 50%;
}
Output:
3.Using Positioning
Combine absolute positioning with the transform function to center both ways.
.container{
position: relative;
height: 100vh;
background-color: lightgray;
}
.center-absolute {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: lightpink;
width: 50%;
text-align: center;
}
Output:
Comparing the Techniques
Each centering technique has its pros and cons, depending on the specific requirements of your design and your personal preference.
Margin: auto;
requires less code and is simple to implement, it is perfect for horizontally centering elements with a fixed width. Flexbox gives you control over the alignment of your elements with properties like align-items
and justify-content
.
CSS Grid being two-dimensional takes things a step further by providing control over both rows and columns at the same time. Positioning is flexible and can be used to center elements regardless of their dimensions or the container's dimensions.
Flexbox and CSS Grid are probably the most versatile methods for centering, as they are modern and suitable for most responsive design needs. A good understanding of the strengths and limitations of each approach will help you make informed decisions when centering.
Coding is a skill, and like all skills, centering divs require some practice. As renowned author Norman Vincent Peale stated:
Nobody ever mastered any skill except through intensive persistent and intelligent practice.
Remember, keep practising and soon you'll be centering divs like a master developer!
Conclusion
From basic CSS properties to more advanced methods, I have covered various ways you can center a div. Understanding the box model principle and exploring the various centering techniques will help you create visually appealing layouts and user-friendly interfaces.
Happy coding besties!
Top comments (0)