- How to center an input field using CSS?
- Method 1: Center an Input Field Using text-align Property
- Method 2: Center an Input Field Using margin: auto
- Method 3: Center an input field using CSS Grids
- Method 4: Center Input Fields using CSS Flexbox(Modern Way)
- Conclusion
- Related posts:
- How to Align the Placeholder Text of an Input Field in HTML
- Create HTML
- Add CSS
- Example of centering an input field’s placeholder text:
- Result
- Example of aligning an input field’s placeholder and placeholder value:
- Example of aligning the placeholder text of an input field:
- How to Align Placeholder text using CSS
- Using placeholder Attribute in a textbox
- CSS ::placeholder Selector
- Syntax
- Browser Compatibility
- Центрирование вводимого текстового поля HTML
- 8 ответов
How to center an input field using CSS?
In HTML, input fields are used inside forms to collect user data. The input fields are actually the most commonly used form elements which can be used to collect various types of user information such as name, email, phone, password, address, etc.
When we are working with these input fields, one common problem that we all face is their centering inside their form or their parent element.
Method 1: Center an Input Field Using text-align Property
Originally, the text-align property is used to align the text of an element to the left, right or center. But, we can also use this property to center our input fields.
Now, you might be thinking if the text-align property aligns only the text of an element, how can it align the inputs?
Well, this works because the input elements( ) are by default inline-block type elements. If an element is of type inline-block, it does not take the full with of its parent. Instead, it takes only as much width as it requires. This is the reason, the text-align property works on inputs.
Let’s say, we have a div element, which contains an input text-box:
To center align the input field inside the div element, we can simply set its text-align property to center in our CSS file:
Below is the outcome of the above code:
When using this approach, you have to keep in mind that this will also center other elements of the div such as the texts, images, links, etc. if any. So use it wisely.
Method 2: Center an Input Field Using margin: auto
The margin property basically specifies a space around the boundaries(outside borders) of an element. But it can also be used to center align things within their container.
All you need to do is apply margin: auto; on the element that you want to center. But there is one important thing that is to be kept in mind, if the element is not a block-level element, applying margin: auto; will not center it.
In that case, you have to explicitly make the element a block-level element by explicitly setting its display property to block .
Let’s take the same example again:
To center align the input field, set its margin to auto along with display: block;
Below is the outcome of the above code:
As you can see, the input is centered inside the div. The main advantage of this method over the previous one is that it only centers those elements on which we apply the margin: auto; . The remaining elements remain untouched.
Method 3: Center an input field using CSS Grids
CSS Grids are a layout system that allows developers to create two-dimensional layouts with rows and columns. We can also use them for alignment purposes.
Let’s say we have a div element which contains an input field. We have also assigned a grid-container class to the div.
To center the input element inside the div, we have to first make the div a grid container which can be done by applying display: grid; property on it.
When you set the display property of an element to grid , the element starts behaving like a grid container. This means that we can now use any grid property on this element.
Now, to horizontally center the input element inside this grid container, you can set the justify-content property to center .
But there is one problem with this method, by default, the grid items take up the full height of the grid container. To stop this, you have to set the align-items property to start . The align-items property is used to align items vertically inside the container.
Method 4: Center Input Fields using CSS Flexbox(Modern Way)
Now a days, CSS flexbox has become the most preffered method when it comes to centering things. CSS flexbox is basically a flexible box layout module that lets you create flexible and responsive layouts without using the float and position properties.
You can also use this method to center input elements with ease. Centering is almost similar to the grids.
If you want to use CSS flexbox, you have to simply set the display property of the element to flex . Aftering applying the display: flex; property, the element starts behaving like a flex container.
Let’s say we have a div element with a class flex-container , which contains an input element:
Now, if we want to center align the input element inside the flex container, we can set the justify-content property to center just like the grids.
Here also, we have to set the align-items property to start or flex-start , so that the flex items do not take the full height of the flex container.
Here is the result of the above code:
If you also want to center the input box vertically, you can set the align-items property to center :
Here is the outcome of the above CSS:
Conclusion
In this article, we learned four different ways to center align input fields, the text-align: center; , the margin: auto , the grids module and the flexbox module of CSS.
You can use any method based on your requirements. However, the modern and simplest way to center things is the flexbox module.
Related posts:
How to Align the Placeholder Text of an Input Field in HTML
The ::placeholder pseudo-element allows styling the placeholder text of a form element. It can change from browser to browser.
The placeholder attribute is used to describe the expected value of an input field. Before entering a value, there is a short hint displayed in the field.
Placeholder texts are commonly aligned to the left in most browsers.
We use the text-align property to set the alignment of text in the placeholder.
In our snippet, we’ll demonstrate step by step how to center a placeholder text.
Create HTML
form action="/form/submit" method="POST"> input type="email" placeholder="info@w3docs.com" name="email" />
Add CSS
- Set the text-align property to «center» for the input.
- Use ::-webkit-input-placeholder for Chrome, Opera, and Safari.
- Use :-moz-placeholder for Firefox 18-.
input < text-align: center; > ::-webkit-input-placeholder < text-align: center; > :-moz-placeholder < text-align: center; >
Now, we can bring together the parts of our code.
Example of centering an input field’s placeholder text:
html> html> head> title>Title of the document title> style> input < text-align: center; > ::-webkit-input-placeholder < text-align: center; > :-moz-placeholder < text-align: center; > style> head> body> form action="/form/submit" method="POST"> input type="email" class="emailField" placeholder="[email protected]" name="email" /> form> body> html>
Result
Let’s see another example, where we use three elements and use the text-align property set to «center», «right», and «left» respectively. In this example, we align both the input field’s placeholder and the placeholder value.
Example of aligning an input field’s placeholder and placeholder value:
html> html> head> title>Title of the document title> style> input[type="email"] < text-align: center; > input[type="text"] < text-align: right; > input[type="tel"] < text-align: left; > body < text-align: center; > label < display: block; margin-bottom: 30px; > style> head> body> form action="/form/submit" method="post"> label>Center Alignment br> input type="email" placeholder="Email"> label> label>Right Alignment br> input type="text" placeholder="Name"> label> label>Left Alignment br> input type="tel" placeholder="Phone Number"> label> form> body> html>
Now, we’ll demonstrate one more example, where our placeholder values are aligned to the center, right, and left, whereas the input starts from the left in all cases.
Example of aligning the placeholder text of an input field:
html> html> head> title>Title of the document title> style> input[type="email"]::placeholder < text-align: center; > input[type="text"]::placeholder < text-align: right; > input[type="tel"]::placeholder < text-align: left; > body < text-align: center; > label < display: block; margin-bottom: 20px; > style> head> body> h1>Placeholder Text Alignment h1> form action="/form/submit" method="post"> label>Center Alignment br> input type="email" placeholder="Email"> label> label>Right Alignment br> input type="text" placeholder="Name"> label> label>Left Alignment br> input type="tel" placeholder="Phone Number"> label> form> body> html>
How to Align Placeholder text using CSS
The HTML5 placeholder attribute is used to show a small hint to describe a value to help users understand what value they should enter in a text field. The placeholder text by default is left aligned. I’ll show you how using CSS, you can align the placeholder text anywhere you want in a text box.
Using placeholder Attribute in a textbox
This is how you add the placeholder attribute to an input box of type text.
<input type=’text’ placeholder =’Enter your name’/>
If you see the output, the placeholder text is by default left aligned. (See the above image)
CSS ::placeholder Selector
You can align the placeholder text (right, left or center) using CSS ::placeholder selector property.
<!DOCTYPE html> <html> <head> <style> input[type='text']::placeholder < text-align: right; /* for Chrome, Firefox, Opera */ > :-ms-input-placeholder < text-align: right; /* for IE 10-11 */ > ::-webkit-input-placeholder < text-align: right; /* for IE Edge */ > </style> </head> <body> <input type='text' placeholder='Enter your name' /> </body> </html>
Syntax
::placeholder
… some css styles here.
>
Now, I’ll extent the above example and use the ::placeholder selector to align placeholder text at the center of the input box.
<style> input[type='text']::placeholder < text-align: center; /* for Chrome, Firefox, Opera */ > :-ms-input-placeholder < text-align: center; /* for IE 10-11 */ > ::-webkit-input-placeholder < text-align: center; /* for IE Edge */ > </style> <input type='text' placeholder='Enter your name' />
See how I have used the ::placeholder selector property inside the <style> tag. Since, the input box is of type text, I have used the type as text .
input[type=’text’]::placeholder
You can change the type to other values. For example, if the input type is email, then the CSS should be,
input[type=’email’]::placeholder
<
text-align: right;
>
<style> input[type='email']::placeholder < text-align: right; /* for Chrome, Firefox, Opera */ > input[type='email']:-ms-input-placeholder < text-align: right; /* for IE 10-11 */ > input[type='email']::-ms-input-placeholder < text-align: right; /* for IE Edge */ > </style> <input type='email' placeholder='Enter Email ID' />
Browser Compatibility
• IE 10 — Yes it worked
• Firefox 62+ — Yes it worked
• Chrome (any) — Yes it worked
• Opera 56+ — Yes it worked
Центрирование вводимого текстового поля HTML
Не совсем ответ, но jQuery Mobile делает это, так что вы можете посмотреть, как они этого добиваются.
Для меня ваш код работает, когда вы избавляетесь от бита input.placeholder . Выравнивание текста внутри ввода по центру также выравнивает заполнитель.
8 ответов
Если вы хотите изменить только стиль заполнителя
::-webkit-input-placeholder < text-align: center; >:-moz-placeholder < /* Firefox 18- */ text-align: center; >::-moz-placeholder < /* Firefox 19+ */ text-align: center; >:-ms-input-placeholder
Это прекрасно работает для большинства полей ввода, но не для даты типа. Вы знаете, как сделать так, чтобы это работало на сегодняшний день?
Рабочий пример в FF6. Этот метод, похоже, не совместим с кросс-браузером.
Ваш предыдущий CSS пытался центрировать текст элемента ввода, который имел класс «placeholder».
Осторожно, если вы используете библиотеки, такие как Bootstrap или Semantic UI, вы должны добавить встроенный стиль, то есть для это на работу. Или добавить important! к вашему правилу CSS, если вы используете внешние файлы.
Похоже, проблема с max_ — это просто проблема совместимости браузера. Это прекрасно работает в большинстве основных браузеров, кроме Safari.
Он отлично работает для моих нужд, вы должны проверить совместимость для своего браузера, У меня не было проблем, потому что я не заботился о обратной совместимости
.inputclass::-webkit-input-placeholder < text-align: center; >.inputclass:-moz-placeholder < /* Firefox 18- */ text-align: center; >.inputclass::-moz-placeholder < /* Firefox 19+ */ text-align: center; >.inputclass:-ms-input-placeholder
Элемент-заполнитель HTML5 может быть стилизован для тех браузеров, которые принимают этот элемент, но по-разному, как вы можете видеть здесь: http://davidwalsh.name/html5-placeholder-css.
Но я не считаю, что text-align будет интерпретироваться браузерами. По крайней мере, в Chrome этот атрибут игнорируется. Но вы всегда можете изменить другие вещи, такие как color , font-size , font-family и т.д. Я предлагаю вам переосмыслить свой дизайн, возможно ли удалить это поведение центра.
Если вы действительно хотите, чтобы этот текст был центрирован, вы всегда можете использовать код jQuery или плагин для имитации поведения заполнитель. Вот пример: http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html.
Таким образом, стиль будет работать: