Как поставить кнопку в центр css
Перейти к содержимому

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

  • автор:

Как выровнять кнопку по центру css

Для выравнивания кнопки по центру относительно родительского элемента мы можем указать следующие CSS свойства у родительского элемента:

display: flex; justify-content: center; align-items: center; 

Свойство justify-content отвечает в данном случае за выравнивание кнопки по горизонтали, а align-items — за выравнивание по вертикали.

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

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

Как только делать кнопке display: inline-block; — то кнопка сразу прилипает к левому краю и никакие text-align: center; не помогают 🙁

Отслеживать
задан 1 ноя 2016 в 11:09
81 2 2 золотых знака 3 3 серебряных знака 10 10 бронзовых знаков
Что такое сделали, что кнопка навидимая?
1 ноя 2016 в 11:16
@Sergey не понял Вас.
1 ноя 2016 в 11:17
Пробовали выполнять свой код? Текст кнопки-ссылки белый, на белом фоне не виден.
1 ноя 2016 в 11:33

3 ответа 3

Сортировка: Сброс на вариант по умолчанию

Как один из вариантов:

.section a < color: white; text-transform: uppercase; text-decoration: none; >.title-text < text-align: center; >.button < display: inline-block; height: 50px; line-height: 50px; position: relative; border: 1px solid white; padding: 0 1rem; >body
 

We are specialist in

Responsive designs, Stationary
And wordpress Themes

Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text.

Button Name

Отслеживать
ответ дан 1 ноя 2016 в 11:23
22.4k 10 10 золотых знаков 56 56 серебряных знаков 119 119 бронзовых знаков
супер!! огромное спасибо!)
1 ноя 2016 в 11:30

Используйте css хаки)

.button < height: 50px; display:block; position: relative; border: 1px solid white; margin:0 auto; // отцентрирует блок по центру родительского элемента >

Отслеживать
ответ дан 1 ноя 2016 в 11:13
Broouzer King Broouzer King
776 1 1 золотой знак 6 6 серебряных знаков 29 29 бронзовых знаков
ни к чему не привело вообще 🙁
1 ноя 2016 в 11:15

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

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

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

.section > div < display: inline-block; >.button < text-align: center; >.button > a < color: #39739d; background-color: #E1ECF4; border: 1px solid #96bdd9; padding: 5px; border-radius: 5px; box-shadow: inset 0 1px 0 #f4f8fb; text-decoration: none; >.button > a:hover
 

We are specialist in

Responsive designs, Stationary
And wordpress Themes

Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text.

Button Name

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

Как выровнять button по центру блока?

Наконец-то смог выставить кнопку по центру, да еще адаптивно!

THANK YOU VERY MUCH. 🙂

chernovairina

Ирина Чернова @chernovairina

Если в блоке только кнопка, тогда вариант отличный. А если есть текст, тогда он и кнопка будут находиться на одно линии

gluck59

Виртуальный глюк

.Absolute-Center

Ответ написан более трёх лет назад
Нравится 4 2 комментария
Очень плохой вариант, тогда будет кликабильна облась слева и справа от кнопки

gluck59

Besenn0k, приходите когда подучите UX.
Vovik_alkogolik @Vovik_alkogolik
margin: 0 auto;
display: block;
Ответ написан более двух лет назад
Комментировать
Нравится 4 Комментировать

nice1231

Мне помог флексбокс:

 
.button-wrapper

Ответ написан более трёх лет назад
Комментировать
Нравится 3 Комментировать
Alexander @AlexBlack666

 .center 

Ответ написан более трёх лет назад
Нравится 2 1 комментарий

Не правильно, Если в блоке поля и подписи к ним? Допустим их нужно будет выровнять по левому краю, а кнопку по середине. С вашим кодом выровняется всё.

heksen

Ilya Bobkov @heksen Автор вопроса
Не работает. Вот код:

 .Absolute-Center 

How To Center A Button In CSS

How To Center A Button In CSS

Buttons are a great way to format your CTAs or other links. Check out this easy guide on centering buttons in CSS.

Let’s get started.

  • Understanding CSS Centering
  • Center A Button Using Flexbox
  • Center A Button Using Grid Layout
  • Vertically and Horizontally Centering
  • Center A Button Using Text Alignment
  • Troubleshooting Common Issues
  • Frequently Asked Questions

    Understanding CSS Centering

    CSS centering can be a bit of a puzzle. There are several ways to center elements, and the method you choose can depend on the context and specific requirements of your layout.

    Block level elements can be centered using the margin property. By setting both the left and right margins to auto , and specifying a width, the element will center itself within its parent. Here’s an example:

    For inline or inline-block elements, the text-align property can be used on the parent element to center them. This is a common method for centering text, but it works for any inline content. Here’s how you can do it:

    Flexbox Centering

    The Flexbox layout module provides a more efficient way to lay out, align and distribute space among items in a container. To center a single item, or a group of items in both the horizontal and vertical axis, you can use display: flex , justify-content: center , and align-items: center on the parent element.

    Grid Centering

    The CSS Grid layout is another powerful tool for centering. It works similarly to Flexbox but is better suited for two-dimensional layouts (rows and columns). To center items in a grid, you can use display: grid , justify-content: center , and align-items: center .

    images

    Centering Text Inside the Button

    If you want to center the text inside the button as well, you can apply text-align: center directly to the button. This will center the text within the button.

    button

    Using text alignment is a straightforward method for centering a button, especially when dealing with text or inline elements. It’s a handy tool to have in your CSS toolkit.

    Troubleshooting Common Issues

    While centering a button in CSS is generally straightforward, you might encounter some common issues. Here are a few troubleshooting tips to help you resolve them.

    Button Not Centering

    If your button is not centering as expected, check the display property of the parent element. For Flexbox and Grid layouts, the parent must have a display property of flex or grid respectively. If it’s set to block or inline-block , the centering properties won’t work. Here’s the correct setup:

    Button Centering Horizontally But Not Vertically

    If your button is centering horizontally but not vertically, it’s likely that the align-items property is missing or incorrect. Make sure it’s set to center :

    Button Not Centering with Text-Align

    If you’re using text-align: center and the button is not centering, check the display property of the button. The text-align property only works with inline or inline-block elements. If the button is a block-level element, you’ll need to change its display property:

    button

    Troubleshooting is a key part of any developer’s workflow. By understanding these common issues and their solutions, you’ll be well-equipped to center buttons in CSS.

    Frequently Asked Questions

    What is the difference between using text alignment and using Flexbox or Grid to center a button in CSS?

    Flexbox and Grid can center a button horizontally and vertically, while text alignment can be used to center a button horizontally.

    Why Isn’t My Button Centering?

    If your button isn’t centering, it could be due to several reasons. The most common issue is not setting the correct display property on the parent element. For Flexbox and Grid layouts, the parent must have a display property of flex or grid respectively.

    Can I Center a Button Vertically and Horizontally at the Same Time?

    Yes, you can center a button both vertically and horizontally at the same time. This can be achieved using either the Flexbox or Grid layout. You need to use both justify-content: center and align-items: center on the parent element.

    Can I Center Multiple Buttons at Once?

    Yes, you can center multiple buttons at once. If the buttons are in the same parent element, applying the centering properties to the parent will center all the child elements, including all buttons.

    If you need more CSS tips and guides? Check out the rest of our tutorials.

    Time to QUIZ!

    Which CSS property is used to center items horizontally in a flex container?

  • Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *