Vertical text alignment in buttons and inputs
Have you ever struggled with vertically aligning the content of your interactive elements? You’re in good company. A lot of us do.
In this article, we’ll look at how to center the content of buttons and input elements using line-height, padding, and flexbox.
So, what’s our goal here?
We want to build a system where:
- the content of buttons and input elements is perfectly aligned
- buttons and input elements have the same height
- font-size, line-height, padding, and border determine the size of buttons and inputs*
*An alternative approach would be setting a fixed height (e.g., height: 40px; ) and a line-height equal to the height value (e.g., line-height: 40px; ) for all buttons and inputs. However, using padding (instead of a fixed height) is safer because the button will adapt to its content under all circumstances.
Basic button and input style #
The height and vertical alignment of buttons and inputs is determined by the combination of borders, padding, font-size, and line-height.
factors influencing button/input height
With that in mind, let’s define the basic style of buttons and inputs:
Takeaway points from the above snippet:
- We set the display value of the buttons equal to inline-flex so that we can use the justify-content and align-items properties to center the content (particularly handy if you place an icon inside a button).
- We apply the same vertical padding, font-size, line-height, and border-width to buttons and inputs.
- Even tough we don’t plan on adding a visible border to the buttons, we apply it anyway (with a transparent color) to make sure buttons and inputs have the same height.
- The line-height value needs to be slightly bigger than «1» . If you use «1», the input elements won’t accept it, and they’ll be taller than the buttons. In our example, we’re applying «1.2» (you could use «normal» if you prefer).
This basic style will ensure buttons and input elements have the same height and that their content is vertically aligned. You can modify their font-size (e.g., set a fixed font-size) or apply a different font-family, and it won’t affect the alignment. After all, we’re just pushing the content using padding and border.
You can also scale them up/down taking advantage of the Em units.
Real-world examples #
Let’s see this technique in action with some real-world examples.
A typical case where you want to align a button with an input field is a newsletter form.
If you are collecting the user email only, the subscribe button can be placed right next to the email input field, as it is done in this newsletter component example.
Use cases of this technique are not limited to newsletter forms.
Consider this repeater component. It can be used to clone and delete a collection of items.
Consider an account form where you want your users to be able to list all their social accounts. They should be able to add multiple social links, and delete them if too many were added. A delete button next to an input field does the trick; and clearly, they should be vertically aligned!
Exceptions #
There may be cases where we need to set a fixed height for our button/input elements, and the default line-height will break the alignment.
In such cases, we can remove the vertical padding and set the line-height equal to the height value.
Here’s a workaround based on creating height utility classes that behaves slightly differently when applied to buttons and inputs:
Feedback? #
Do you use a different method you’d like to share? Let us know on Twitter!
Cookie Compliance
We use cookies to give you the best possible website experience. By using CodyHouse, you agree to our Privacy Policy.
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.
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.
Текст расположить по центру кнопки
Как расположить текст вертикально по центру к <label>?
Есть стилизованный переключатель, мне нужно отцентровать текст по вертикали, кто подскажет как это.
Расположить кнопки по центру в столбик
Всем доброго времени суток. Друзья, как шамать с Layout`s, что бы расположить кнопки по центру.
Расположить текст по центру
<TextView android:id="@+id/textView8" android:layout_width="match_parent" .
Расположить текст по центру в Edit
текст по центру в Edit — минимальный пример пожалуйсто есть ответы — сделать компонент.
Как выровнять кнопку по центру используя 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 на веб-странице, а кнопка находится внутри родительского элемента.