Html form по центру

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.

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.

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.

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.

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.

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), а потом через медиа запросы поменять, но это уже второстепенная задача.

Источник

Center a Form in HTML

Center a Form in HTML

  1. Use the CSS margin Property to Center a Form in HTML
  2. Use the CSS text-align Property to Center a Form in HTML
  3. Use the CSS width and margin-left Properties to Center a Form in HTML

This article will introduce methods to center a form in HTML.

Use the CSS margin Property to Center a Form in HTML

We can use the margin CSS property to center a form in HTML.

The styles can be written as an inline CSS in the form tag. The margin property defines the space between the container and the adjacent elements.

First, we can provide the value to set a margin for the property. When we use a single value, the value applies to all four directions of the container.

Next, we can use the auto value for the margin property to center the form. For this, we should provide a width of the form for it to be adjusted in the center with the given width.

The auto value will split the remaining distance equally from the left and the right.

For example, create a form tag write the style attribute in it. In the style attribute, set the margin property to auto and the width property to 220px .

Next, create an input tag of text and another input tag of submit .

The example below will create a centered form. The form has a width of 220px , and the remaining space is divided into left and right margins.

In this way, we can create a form with center alignment with margin:auto using CSS in HTML.

form style="margin: auto; width: 220px;">  Enter name:input type="text" />  input type="submit" value="Submit"/>  form> 

Use the CSS text-align Property to Center a Form in HTML

We use the text-align property to specify the alignment of the text in CSS. We can use the property as an inline style of the form tag to set the alignment of the form.

The text-align property takes the values like left , right , center , justify , etc. We can set the value to center to center the form.

For example, apply the text-align property to the form tag in the style attribute, and set the property to center . Next, create input tags with the type text and then submit .

The example below will center all the contents of the form. However, the form occupies the whole block as no margin has been specified.

In this way, we can center the form in HTML.

form style="text-align: center; ">  Enter name:input type="text"/> br>br>  input type="submit" value="Submit"/>  form> 

Use the CSS width and margin-left Properties to Center a Form in HTML

We can set the form’s width as 50% of the viewport width, and then we can provide 25% of the width as margin to the left. We can use the width and margin-left CSS properties to set the width and margin and achieve our goal.

Finally, we can use the vw unit to specify the length. For example, set width to 50vw and margin-left to 25vw as the style attribute of the form tag.

Here, the value 50vw will occupy 50% of the viewport width, and the value 25vw will give 25% of the viewport width as the left margin. The remaining 25% space will be in the right of the form.

In this way, we can center a form in HTML.

form style=" width: 50vw; margin-left : 25vw;">  Enter name:input type="text"/> br>br>  input type="submit" value="Submit"/>  form> 

Источник

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