Как расположить кнопку по центру css

от admin

Как выровнять кнопку по центру используя 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

This tutorial explains how to center the CSS button.

CSS Center Button

The main aim of CSS (Cascading Style Sheets) is to provide the best style for an HTML web page. Using CSS you can specify the arrangement of all the elements of the page. You can align elements both horizontally and vertically. A CSS button needs to be centre aligned if you want it to be centrally positioned within a div or at the centre of the web page.

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.

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 th text-align property of the parent div tag to the center

In this example, we are using text-align: center property to the parent div and button position 50% from top «top: 50%;«.

Code:

Output:

3.2: By setting position property to 50% from top and bottom

In this example, we are using position property to <button> tag with left: 50% & top: 50%

Code:

Output:

3.3: By setting margin property to auto

In this example, we are using margin: auto CSS property to <button> tag

Code:

Output:

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 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.

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.

7. Using CSS Bootstrap

In CSS Bootstrap we can use class «text-center» as given in the example

Как сделать кнопку по центру?

введите сюда описание изображения

inline-block заставляет контейнер (div в данном случае) съёжится до размеров того, что в нём находится. Таким образом text-align не годится для выравнивания содержимого внутри inline-block . Ибо ему просто некуда двигаться. Размеры-то одинаковые.

Если div шире своего содержимого, то text-align работает.
Но Ваш кнопочный div, когда он нормальный block, растягивается по длине на всю ширину страницы. Поэтому кнопка выравнивается относительно страницы и уезжает правее относительно центра текста.

Можно сузить общий контейнер для текста и кнопки с помощью того же inline-block . Он не будет шире текста (предполагаем текст шире кнопки), кнопочный div таким образом тоже по ширине будет как текст, и кнопка теперь выравнивается относительно текста.

Понадобилось правильно установить всего два свойства css. Они самые первые. Остальное для красоты, если это кому-то нравится. Правда есть ещё элемент ubasility. Кнопка работает при нажатии не только по надписи, но и по всей области кнопки. Пользователю не надо быть снайпером.

How TO — Center a Button in DIV

Learn how to center a button element vertically and horizontally with CSS.

How To Center a Button Vertically

Example

<style>
.container <
height: 200px;
position: relative;
border: 3px solid green;
>

.vertical-center <
margin: 0;
position: absolute;
top: 50%;
-ms-transform: translateY(-50%);
transform: translateY(-50%);
>
</style>

How To Center Vertically AND Horizontally

Example

<style>
.container <
height: 200px;
position: relative;
border: 3px solid green;
>

.center <
margin: 0;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
>
</style>

You can also use flexbox to center things:

Example

Tip: Go to our CSS Align Tutorial to learn more about aligning elements.

Tip: Go to our CSS Transform Tutorial to learn more about how to scale elements.

Tip: Go to our CSS Flexbox Tutorial to learn more flexbox.

Get started with your own server with Dynamic Spaces

COLOR PICKER

colorpicker

Get certified
by completing
a course today!

Subscribe

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Related Posts