Расположить форму html по центру

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:

Center an input field using text-align property

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.

Читайте также:  Экспорт psd в html

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;

Center an input using margin auto

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.

Center an input field using CSS grids

… And here is the result:

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.

Читайте также:  Load texture in java

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.

Center input using CSS flexbox

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 :

Perfectly center input using CSS flexbox

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.

Источник

How to center a HTML form in CSS

The best way to center a form horizontally in HTML and CSS is by using CSS flexbox. It is responsive and works well on mobile, tablet and desktop view.

Previously, we used to rely on methods that seemed like some CSS hacks. CSS flexbox came to solve such problems.

How to center a HTML form in a Div horizontally using CSS Flexbox

You need a form with it elements already created. For my case I will use.

  Email:  type="email" name="email" placeholder="Email">  type="submit">  

Uncentered HTML form

Wrap your form element in a div tag.

   Email:  type="email" name="email" placeholder="Email">  type="submit">   

Add a class to the div html tag that will be used to center the form.

 class="form-center">  Email:  type="email" name="email" placeholder="Email">  type="submit">   

Add the CSS flexbox to the class form-center.

.form-center  display:flex; justify-content: center; > 

centered HTML form

Test your form. It should be centered. You can also check the results of centering using CSS flexbox.

Full Centered Form HTML CSS Flexbox Code

 class="form-center">  Email:  type="email" name="email" placeholder="Email">  type="submit">   
.form-center  display:flex; justify-content: center; > 

How to center a form horizontally using CSS margin

.form-center  width:400px; margin: 0 auto; > 

This was by far the most used method in centering block level elements like forms in HTML and CSS.

How to center a form horizontally using absolute CSS positioning

You wrap a div with a class of form-center around the form element.

 class="form-center">  Email:  type="email" name="email" placeholder="Email">  type="submit">   

You give the div tag relative positioning and set its width and height. You have to set the width and height, otherwise this will not work.

.form-center  position: relative; width:100%; height:10em; > 

Now you can add the CSS to position the form at the center of your container.

.form-center form  position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); > 

author

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.

Front End Developer Newsletter

Receive a monthly Frontend Web Development newsletter.
Never any spam, easily unsubscribe any time.

About

If you are just starting out you can test the waters by attempting the project-based HTML tutorial for beginners that I made just for you.

Okay, you got me there, I made it because it was fun and I enjoy helping you on your learning journey as well.

You can also use the HTML and CSS projects list as a source of projects to build as you learn HTML, CSS and JavaScript.

Start understanding the whole web development field now

Stop all the confusion and start understanding how all the pieces of web development fit together.

Never any spam, easily unsubscribe any time.

Recent Posts

Источник

Как выровнять форму по центру?

6331e7161ab65707002530.png

Надо так:

.register__inner < display: grid; grid-template-columns: 1fr 2fr; border: 1px solid black; >.register__form < display: grid; grid-template-columns: 1fr 1fr; >.register__input < width: 380px; height: 65px; border: 1px solid #d8d8d8; border-radius: 5px; padding: 27px 24px 23px; margin-bottom: 28px; >.register__btn

6331e7897de3b610765918.png

Получается следующие:

Простой 2 комментария

AlekSays

Вам стоит лучше подучить гриды.
`register_inner` для чего использует гриды?
Фиксированные значения для элементов формы это плохо, тем более если используете гриды.
В примере что по ссылке я использовал фиксированные значения для register_inner, но советовал бы использовать все таки %.
Если будут вопросы пишите в комментариях к ответу

Ankhena

Объясните мне вот что:
Для register__inner вы задаете grid-template-columns: 1fr 2fr;
Внутри один дочерний элемент, у которого все свойства грид-элемента по умолчанию.
Т.е. он займет 1 колонку.
Эта колонка занимает одну треть родителя.

Как после всего написанного форма должна оказаться по центру родителя?

Все способы центрирования — выбирайте любой.
Самый простой margin-inline: auto (ну или записью по-старинке, если ТЗ не позволяет, сути не меняет)

mizutsune

Устанавливать фиксированные значения для свойства width — не совсем корректно. Да и к тому же вы используется гриды, не совсем так как нужно.

Немного подправил ваши стили:

.register__inner < width: 100%; >.register__form < width: 100%; max-width: 1000px; margin: 0 auto; display: grid; grid-template-columns: repeat(auto-fill, minmax(400px, 1fr)); grid-gap: 10px; >.register__input < width: 100%; height: 65px; border: 1px solid #d8d8d8; border-radius: 5px; padding: 27px 24px 23px; >.register__btn

У элемента .register__form в принципе можно установить значение grid-template-columns: repeat(2, 1fr), а потом через медиа запросы поменять, но это уже второстепенная задача.

Источник

Оцените статью