How to center things with CSS

29 Nov, 2018

Being able to center text, divs and images is one of the most important things that you can utilize to create clean and modern websites. However, there are a few different ways to go about the problem, depending on the situation.

For centring text, it's pretty straightforward. One line is all you need to get the job done.


h1{
  text-align: center;
}
		

Next, if you need to center a div or image you can use auto margins on the left and right. This technique will only work if the div/image has display: block.


#some_div{
  display: block;
  margin: 0 auto;
}
		

Last but definitely not least, if you need to center an element both horizontally and vertically or your working with positioned elements, for example absolute, or fixed etc. Then the previous method won't be of much help. Instead, you will need to center the element with top/bottom/left/right and then shift the element back 50% of its width and height.


#some_div{
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
		

Other Tutorials

View All

Detecting system dark mode in CSS

css


The "dark mode" feature has been spreading to apps and websites far and wide recently. It brings a new and discrete look to your applications as well as offering some extra control to the user...

Essential meta tags for the modern internet

html


Meta tags give you the power to customise how your site appears to the rest of the internet. They provide a simple and fast way for web crawlers and other applications to get information about a website.

Immersive Parallax scrolling effect

javascript - css - html


You might have noticed while moving along in a car or train, how far away objects seem to move across your vision slower than those closer to your eyes. This effect is known as parallax and its a fundamental aspect of vision which can often go unnoticed.