HTML/CSS: How-to Centre Your New CTA Button

mark l chaves
3 min readApr 28, 2019

--

This article shows two ways to centre a custom call-to-action button using HTML & CSS.

Special thanks to Irene Dang for asking me how to centre my custom CTA button in my earlier article. Ok, let’s get to it!

TL;DR

Scroll all the way to the bottom for the link to the full source code covered in this article.

Two Options to Centre Your Button

There are several ways to do this. I’m going to cover two options.

  1. Option 1: More, Intuitive, & Slick. Option 1 uses a DIV tag. There’s more code involved here, but IMHO (in my humble opinion) it’s more intuitive and elegant. It’s also using the slick CSS Flexible Box (flexbox). Read more on the flexbox here.
  2. Option 2: Minimalist, Cryptic, Oldie but a Goodie. Minimalist is nice when you want to reduce your code footprint (smaller file size). But, code reduction can/will make your code harder to read. Therefore, harder to maintain. This is a tried and trusted method. So, it can be more reliable than option 1. Ah, trade-offs. What can you do?

Centre Option 1: DIV Tags Before & After Your Button Code

Raw Code for Option 1
Marked-up Code for Option 1

Instructions

Copy and paste the first DIV before your button code. Then, copy/paste the closing DIV after your button code. See the marked-up code graphic above.

Here’s the exact code you should be adding as shown above.

<div style=”display: flex; justify-content: center;”>

</div>

Centre Option 2: Adding to Your Existing CSS

Raw Code for Option 2
Marked-up Code for Option 2

Instructions

Simply add the highlighted code above to your existing CSS for your button. I.e. copy/paste what you see here between the single quotes ‘margin: 0 auto;’. This includes the semicolon at the end.

Adding something to your existing CSS means this code must be in between the double quotes (“) that follow the style= inside your button HTML code.

Here’s the exact code again.

margin: 0 auto;

Just Want to Copy/Paste the Full Source?

The full source for this sample code is up on CodePen. Or, click on the CodPen embed below. Once you see the HTML button, click on it to view the HTML source.

Full code for this example is freely available on CodePen.

Please share & enjoy!

Since You Made it This Far

You might be ready to dabble in DIY responsive buttons. Here are links to two CodePens that show two different responsive designs for this exact button.

  1. Responsive Button Without Using a Media Query
  2. Responsive Button Using a Media Query

Adding CSS to WordPress

Are you on WordPress and you want to move your CSS out of the inline HTML? Then, learn how to add CSS to WordPress here!

--

--

mark l chaves

I slung code for Fortune 500 companies in a previous life. Now, I write and make some photographs. I’ve moved on to Dev.to. Portfolio on CaughtMyEye.cc