Как выровнять формы в html
Перейти к содержимому

Как выровнять формы в html

  • автор:

Выравнивание элементов формы на flex

Выравнивание элементов формы на flex

С технологией флексбоксов стало намного проще не только адаптивно верстать сайты, но и выравнивать элементы. Раньше с этим было трудновато. Давайте посмотрим как можно легко и красиво на флексбоксах выровнять элементы формы.

HTML разметка формы

Обернем форму в блок с классом form__wrapper. Сформируем ряды формы из маркированных списков. Один ряд соответствует одному тегу li. Внутри тегов li поместим метки (label) и поля ввода (input). В общей сложности у нас будет 4 ряда, в последнем из которых — кнопка (button).

CSS стили для формы

Пускай контейнер для формы будет шириной в 300 пикселей с отступом в 20 пикселей от нижнего края браузера и по горизонтали расположен в центре.

.form__wrapper <
width: 300px;
margin: 20px auto;
background-color: #f5f5f5;
border-radius: 5px;
font-size: 16px;
>

Убираем маркерные дефолтные точки.

ul <
list-style-type: none;
>

Чтобы текст и поля ввода не прилипали к краям контейнера и друг к другу, зададим общему ряду, блоку для меток и инпуту внутренние отступы.

.form__line <
padding: 8px;
>

.form__line > label <
padding: 8px 16px 8px 0;
>

.form__line > input <
padding: 8px;
>

Немного приукрасим кнопку.

.form__row > button <
background: #808080;
color: #fff;
border: 5px;
padding: 8px;
>

Без какого-либо выравнивания наша форма будет выглядеть неаккуратно: поля формы и кнопка стремятся прибиться к правому краю. Такое поведение для элементов формы естественное однако, нас оно совершенно не устраивает. В любом случае, вряд ли дизайнер вот такое безобразие допустит на макете для заказчика. Поэтому необходимо знать, как управлять элементами формы при верстке.

Выравнивание элементов формы на flex.

Флекс форма

Далее сделаем из обычной формы, флекс форму (гибкую). Свойство justify-content прибъет к левому краю, хаотично разбросанные поля ввода. Создадим из класса form__line, четыре flex-контейнера.

.form__line <
display: flex;
justify-content: flex-end;
>

Выравнивание элементов формы на flex.

Первые три flex-контейнера заполнят flex-элементы (label + input), а последний контейнер — кнопка.

Выравнивание элементов формы на flex.

Добавим сокращенную запись flex: 1 к меткам, а для полей ввода flex: 2. Эти свойства управляют размерами элементов, делят между собой свободное пространство в соотношении 1 к 2. В этой статье, вы можете почитать о том, как работают flex-grow, flex-shrink и flex-basis.

.form-line > label <
flex: 1;
>
.form-line > input <
flex: 2;
>

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.

Uncentered HTML form

Wrap your form element in a div tag.

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

Add the CSS flexbox to the class form-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

How to center a form horizontally using CSS margin

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.

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.

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

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.

Share or support on:

Front End Developer Newsletter

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

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.

Выравнивание полей формы с помощью CSS

Добиться, чтобы поля ввода находились друг под другом, и при этом их положение определялось максимальной длиной заголовка поля слева. Решение не должно использовать таблиц и JavaScript.

forms_1

Решение

Шаг первый

<div >
<label for=»n»>Имя</label>
<input type=»text» />
</div>
<div >
<label for=»ln»>Фамилия</label>
<input type=»text» />
</div>
<div >
<label for=»a»>Место жительства</label>
<input type=»text» />
</div>

forms_2

Шаг второй

Выровняем содержимое каждого дива по правому краю и назначим ему обновление потока.

forms_6

Шаг третий

Заставим каждый элемент label «утечь» влево.

Теперь каждый заголовок встал напротив соответствующего поля, но ширина формы стала 100% от ширины родительского элемента.

forms_4

Шаг четвертый

Для того, чтобы прижать поля к заголовкам, обернём всю конструкцию блоком:

<div >
<div >
<label for=»n»>Имя</label>
<input type=»text» />
</div>
<div >
<label for=»ln»>Фамилия</label>
<input type=»text» />
</div>
<div >
<label for=»a»>Место жительства</label>
<input type=»text» />
</div>
</div>

Добавим в CSS обтекание для этого блока:

forms_5

Шаг пятый

Теперь видно, что из-за float элементы перестали находится на одной линии. Vertical-align, к сожалению, работать не будет, но можно воспользоваться line-height.
Также зададим отступ между заголовком и полем:

forms_1

Работающий вариант можно посмотреть здесь. А также заходите на сайт piumosso ))

How to align input forms in HTML

I’m new to HTML and I’m trying to learn how to use forms.

The biggest issue I am having so far is aligning the forms. Here is an example of my current HTML file:

The problem with this is, the field box after ‘Email’ is drastically different in terms of spacing compared to first, and last name. What is the ‘proper’ way to make it so that they ‘line-up’ essentially?

I am trying to practice good form and syntax. a lot of people might do this with CSS I am not sure, I have only learned the very basics of HTML so far.

17 Answers 17

The accepted answer (setting an explicit width in pixels) makes it hard to make changes, and breaks when your users use a different font size. Using CSS tables, on the other hand, works great:

And if you need the labels right-aligned, just add text-align: right to the labels: http://jsfiddle.net/DaS39/

EDIT: One more quick note: CSS tables also let you play with columns: for example, if you want to make the input fields take as much space as possible, you can add the following in your form

you may want to add white-space: nowrap to the labels in that case.

Another example, this uses CSS, I simply put the form in a div with the container class. And specified that input elements contained within are to be 100% of the container width and not have any elements on either side.

A simple solution for you if you’re new to HTML, is just to use a table to line everything up.

I find it far easier to change the display of the labels to inline-block and set a width

Byron's user avatar

You should use a table. As a matter of logical structure the data is tabular: this is why you want it to align, because you want to show that the labels are not related solely to their input boxes but also to each other, in a two-dimensional structure.

[consider what you would do if you had string or numeric values to display instead of input boxes.]

For this, I prefer to keep a correct HTML semantic, and to use a CSS simple as possible.

Something like this would do the job :

One drawback however : you might have to pick the right label width for each form, and this is not easy if your labels can be dynamic (I18N labels for instance).

kleopatra's user avatar

this give you something like:

Gjaa's user avatar

I’m a big fan of using definition lists.

They’re easy to style using CSS, and they avoid the stigma of using tables for layout.

40px left margin), and avoids any semantic confusion. Besides, neither of these line up the labels/inputs on the same line.

It also can be done using CSS and without tables or floats or fixed lengths by changing the content direction to rtl and then back to ltr , but the labels must go after each input.

To avoid this markup reordering, just set the label’s text in a data-* attribute and show it using an ::after pseudo-element. I think it becomes much clearer.

Here is an example setting the label’s text in a custom attribute called data-text and showing them using the ::after pseudo-element, so we don’t mess with markup while changing direction to rtl and ltr :

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

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