HTML/CSS: How-to Centre Your New CTA Button
![]()
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;”>
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!
Как расположить кнопку в опр точке html
Как расположить кнопку в определенной точки. Что бы она не меняла свое положение, даже при разных разрешениях экрана?
top и left в пикселях указать а не в процентах?
А как узнать точное расположение пикселей на картинке или подгонять нужно на глаз?
Кнопка при скроллинге как вести себя должна?
Никак, если возможно вообще без скролла сделать. На странице там обычный фон а на фоне кнопка расположена. При увеличение разрешение кнопка уходит
Т.е. мы делаем div в виде блока и отступы margin сверху 10px справа 0 снизу 10px слева 20px.
Если надо кнопку расположить справа например то можно использовать position: absolute; и задать отступы в виде right: 10px; top: 10px;
Делаете блок, задаете ему position:relative. В него Вашу кнопку с position:absolute, а также right и top. При скриллинге все норм, так как у Вас блок не position:fixed.
Хотя может Вам фиксированный и нужен, я не знаю. В общем-то и все на этом.
Кнопку сделал как надо, только теперь изображение при увеличение разрешение все время уезжает вниз. Не получается привязать кнопку к изображению 🙁
Как выровнять кнопку по центру используя CSS и HTML
Чтобы расположить кнопку в центре HTML страницы, можно использовать 3 разных подхода:
- margin: auto
- div
- flexbox
Разберем их подробнее.
Как использовать margin: auto для центрирования кнопки
Первый и, возможно, самый простой вариант — добавить кнопке CSS свойство margin: 0 auto , а затем добавить display: block , чтобы сделать кнопку в центре.
margin: 0 auto — это краткая форма установки верхнего и нижнего полей в 0 и левого и правого полей на авто.
Автоматическое поле — это то, что заставляет кнопку центрироваться. Тут важно, чтобы кнопка находилась внутри блока.
Как центрировать кнопку с помощью HTML тега div
Второй вариант — обернуть кнопку тегом div , а затем использовать text-align: center для центрирования кнопки внутри этого <div> .
Как будто ты размещаешь текст по центру.
Обратной стороной этого подхода является то, что каждый раз, когда ты хочешь центрировать кнопку, тебе придется создавать новый элемент div только для этой кнопки.
А если у тебя много кнопок, которые требуют частого обновления стиля, поддерживать их быстро становится проблемой.
В таком случае лучше использовать первый вариант.
Короче говоря, если вы настаиваете на использовании этого подхода, сделайте это только для редких кнопок.
Как центрировать кнопку с помощью CSS flexbox
Третий вариант — использовать flexbox для центрирования кнопки.
Этот подход идеален, если ты уже используешь flexbox на веб-странице, а кнопка находится внутри родительского элемента.
Center Align CSS Button
Styling and formatting are what all web developers and designers want to apply to their web pages and application to look attractive. It is up to the creator how they want to use Cascading Style Sheets and Hypertext Transfer Protocol to provide the best style for their web page and application.
Users specifically use CSS to add the best attractive look to their web pages and specify the arrangements of the page elements in a systematic order. This article will discuss how to center a button in the HTML page using CSS.
You can Center Align CSS Button using the following method:
1. By placing a text-align property of body tag to the center (text-align: center)
In this example, we are using `text-align` center property on the <body> tag, so everything inside the <body> tag will be center-aligned automatically.
.png)
1.1 By setting text-align property of parent div tag to the center (text-align: center)
In this example below, we are using `text-align` center property on <div> tag with a class ( button-container-div ) so everything inside this <div> will be center-aligned automatically.
2. Center CSS Button by using margin auto (margin: auto)
In this example, we are using the `margin` auto property. Margin auto moves the div to the center of the screen.
Output:
3. Center Button Vertically AND Horizontally
3.1: By setting the text-align property of the parent div tag to the center
We use the text-align property with the parent div tag to align the button to the center. Let us grab a look at this CSS code snippet and understand how to align the button to the center of the HTML page using CSS
In this example, we are using text-align: center property to the parent div and button position 50% from top «top: 50%;«.
Code:
Output:
In this example, we have used HTML and CSS to align the button on the web page to the center. Here, we discuss the code block in detail:
We have assigned the style information of the button using the HTML <style> tag. The text-align property of CSS aligns the inline-level content (here button) to a horizontal alignment. In this example, we used text-align: center property to the parent div and button position 50% from top «top: 50%;».
Then, we used the HTML <div> tag that acts as a container of the CSS text-align property. Lastly, we added a button on the web page using the HTML <button> tag. The web page will look like this:
3.2: By setting position property to 50% from top and bottom
We assigned only one property to the button element in the earlier example. This example will show two positions for the top and bottom. We use position property to <button> tag with left: 50% & top: 50%
Code:
Output:
Explanation:
The above example shows how to align the button in the HTML page using two position properties of the CSS element. Here, we set the position property as «fixed» and align the button to the center using two properties, namely left and top — to 50%. Finally, we used the HTML <button> tag inside the <div> tag to create the main page button.
3.3: By setting margin property to auto
In this example, we are using margin: auto CSS property to <button> tag
Code:
Output:
Explanation:
In this example, we are using margin: auto CSS property to <button> tag. This property will set the alignment of the CSS button with white spaces. The margin property creates spaces around elements, and we are assigning it to «auto.» Inside the button element of the <style> tag, we add some styles using properties like height, width, top, bottom, left, right, and position that define the button alignment. Finally, we add the HTML <button> tag inside the <div> tag to create the main page button.
4. Center CSS Button using Position fixed
In this example, we are giving a 50% margin from the left side of the page, and then we are taking the position: fixed so it will adjust the position on the center of the body.
Output:
5. By setting the display property to flex (display: flex)
In this example we are using `display` flex property, `justify-content` and `align-items` to the parent <div> tag with class (button-container-div). The button inside <div> will take place in the center of vertical and horizontal position.
- Display flex will move it to the center vertically.
- Justify-content will move the button to the center horizontally.
- Align-items center keeps it in the center; otherwise, it will start from the div and go at the bottom of the div.
Output
6. By setting the display property to the grid (display: grid)
In this example, we are using `display` grid property on the <div> tag with class ( button-container-div ). The button inside <div> will take place in the center of vertical and horizontal positions.
Output
7. Using CSS Bootstrap
In CSS Bootstrap we can use class «text-center» as given in the example
Code:
Output:
Explanation:
We will see how to use the CSS Bootstrap with the class «text-center» in this last example. Inside the <div> button, we used the <button> tag with type and class attributes. The rel attribute of the <link> tag defines the relation between the current and the linked document.
The integrity attribute allows the browser to check the fetched script, and the crossorigin attribute sets the request mode to an HTTP CORS Request.
Conclusion:
We hope this article has given a crisp idea of how to align the button in the HTML page using different approaches to CSS. We have shown alignment vertically and horizontally using text-align, margin, and position properties of the <style> tag in HTML and CSS Bootstrap.