HTML/CSS: How-to Centre Your New CTA Button
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.
- 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.
- 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
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
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.
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.
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!