Красивая страница авторизации. HTML Формы


Здравствуй, дорогой хабрадруг! В этом туториале мы научимся создавать две формы HTML5: форма входа и форма регистрации. Эти формы будут меняться друг с другом местами с помощью псевдо-класса CSS3 :target . Мы будем использовать CSS3 и шрифт с иконками. Идея этого демо в том, чтобы показать пользователю форму входа и предоставить ему ссылку “перехода” к форме регистрации.
В этом туториале я подробно расскажу о том, как создавать эффект как в Демо 1 . HTML Log in

Your email or username

Your password

Keep me logged in

Sign up

Your username

Your email

Your password

Please confirm your password


Здесь мы использовали несколько приемов HTML5. Например, элемент type=password автоматически скрывает то, что пользователь печатает и заменяет символы точками или звездочками (зависит от браузера). Элемент type=email позволяет браузеру проверить правильность формата email адреса. Кроме того, мы использовали параметр require=required ; браузеры, поддерживающие данный параметр не позволят пользователю отправить форму до тех пор, пока поле не заполнено, JavaScript здесь не требуется. Параметр autocomplete=on будет автоматически заполнять некоторые поля. Мы также использовали замещающийся текст, который поможет пользователю при заполнении формы.

Теперь о двух хитрых моментах. Вы наверное заметили две ссылки в начале формы. Этот ловкий прием позволит нашей формы вести себя правильно при работе с якорями (anchors).

Второй момент связан с применением шрифта с иконками. Мы будем использовать data-attribute , чтобы отобразить иконки. Устанавливая параметр data-icon=”icon_character” с соответствующим символов в HTML, мы должны назначить лишь одно правило в CSS для установления стиля всех иконок. Подробнее об этом приеме можно почитать на сайте: 24 Ways: Displaying Icons with Fonts and Data- Attributes .

CSS Для чистоты кода я пропущу базовые параметры (html, body и т.п.), но вы сможете найти их в исходных файлах. Повторяю, что я использую приемы CSS3, которые не будут работать во всех браузерах. Итак, давайте же приступим!Стилизуем формы, используя CSS3 Во-первых, давайте назначим нашим формам базовый стиль.

#subscribe, #login{ position: absolute; top: 0px; width: 88%; padding: 18px 6% 60px 6%; margin: 0 0 35px 0; background: rgb(247, 247, 247); border: 1px solid rgba(147, 184, 189,0.8); box-shadow: 0pt 2px 5px rgba(105, 108, 109, 0.7), 0px 0px 8px 5px rgba(208, 223, 226, 0.4) inset; border-radius: 5px; } #login{ z-index: 22; }

Здесь мы назначим свойства для шапки:

/**** текст ****/ #wrapper h1{ font-size: 48px; color: rgb(6, 106, 117); padding: 2px 0 10px 0; font-family: "FranchiseRegular","Arial Narrow",Arial,sans-serif; font-weight: bold; text-align: center; padding-bottom: 30px; } /** На донный момент только webkit поддерживает background-clip:text; **/ #wrapper h1{ background: -webkit-repeating-linear-gradient(-45deg, rgb(18, 83, 93) , rgb(18, 83, 93) 20px, rgb(64, 111, 118) 20px, rgb(64, 111, 118) 40px, rgb(18, 83, 93) 40px); -webkit-text-fill-color: transparent; -webkit-background-clip: text; } #wrapper h1:after{ content:" "; display:block; width:100%; height:2px; margin-top:10px; background: linear-gradient(left, rgba(147,184,189,0) 0%, rgba(147,184,189,0.8) 20%, rgba(147,184,189,1) 53%, rgba(147,184,189,0.8) 79%, rgba(147,184,189,0) 100%); }

Замечу, что сегодня только браузеры с webkit поддерживают background-clip: text , поэтому мы сделаем полосатый фон только для webkit и привяжем его к заголовку H1. Так как параметр background-clip: text работает только в Webkit браузерах, я решил работать только со свойствами webkit. Именно поэтому я разделил CSS на две части и использовал только градиент webkit. Однако вы не должны использовать лишь webkit на своих вебсайтах! Так, например, параметр -webkit-text-fill-color: transparent позволяет нам иметь прозрачный фон, но только для браузеров webkit, все другие браузеры проигнорируют это свойство.

Мы также создали тонкую линию под заголовком с помощью элемента:after pseudo-class. Мы использовали градиент с 2px в высоту и уменьшили прозрачность по краям до нуля.

Теперь давайте позаботимся о полях ввода и придадим им приятный вид.

/**** advanced input styling ****/ /* placeholder */ ::-webkit-input-placeholder { color: rgb(190, 188, 188); font-style: italic; } input:-moz-placeholder, textarea:-moz-placeholder{ color: rgb(190, 188, 188); font-style: italic; } input { outline: none; }

Во-первых, мы стилизуем поля и уберем обводку. Но будьте осторожны: обводка помогает пользователю понять, на каком поле он находится. Если же вы уберете ее, то нужно применить свойства:active и:focus.

/* все поля исключают submit и checkbox */ #wrapper input:not(){ width: 92%; margin-top: 4px; padding: 10px 5px 10px 32px; border: 1px solid rgb(178, 178, 178); box-sizing: content-box; border-radius: 3px; box-shadow: 0px 1px 4px 0px rgba(168, 168, 168, 0.6) inset; transition: all 0.2s linear; } #wrapper input:not():active, #wrapper input:not():focus{ border: 1px solid rgba(91, 90, 90, 0.7); background: rgba(238, 236, 240, 0.2); box-shadow: 0px 1px 4px 0px rgba(168, 168, 168, 0.9) inset; }

Здесь мы использовали псевдо класс:not, чтобы стилизовать все поля, кроме чекбоксов. Кроме того, я решил убрать обводку и добавил свойства:focus и:active.

Теперь время веселиться: шрифт с иконками. Так как мы не можем использовать псевдо-классы:before и:after, мы добавим иконку в параметр label, а затем разместим в поле. Я буду использовать библиотеку fontomas . Вы можете сами сопоставить иконки с соответствующей буквой. Помните атрибут data-icon ? Именно в него нужно вставить букву. Я использовал data-icon=’u’ для логина, ‘e’ для email, ‘p’ для пароля. Как только я выбрал буквы, я скачал шрифт и использовал генератор шрифтов fontsquirrel для конвертации в формат, пригодный для @font-face.

@font-face { font-family: "FontomasCustomRegular"; src: url("fonts/fontomas-webfont.eot"); src: url("fonts/fontomas-webfont.eot?#iefix") format("embedded-opentype"), url("fonts/fontomas-webfont.woff") format("woff"), url("fonts/fontomas-webfont.ttf") format("truetype"), url("fonts/fontomas-webfont.svg#FontomasCustomRegular") format("svg"); font-weight: normal; font-style: normal; } /** магический трюк! **/ :after { content: attr(data-icon); font-family: "FontomasCustomRegular"; color: rgb(106, 159, 171); position: absolute; left: 10px; top: 35px; width: 30px; }

Вот собственно и все. Вам не требуется иметь отдельный класс для каждой иконки. Мы использовали параметр content: attr(data-icon) , чтобы получить букву из атрибута data-icon. Таким образом, нам нужно лишь назначить шрифт, выбрать цвет и разместить иконку.

Теперь назначим правила для кнопки отправки формы.

/*стилизуем обе кнопки*/ #wrapper p.button input{ width: 30%; cursor: pointer; background: rgb(61, 157, 179); padding: 8px 5px; font-family: "BebasNeueRegular","Arial Narrow",Arial,sans-serif; color: #fff; font-size: 24px; border: 1px solid rgb(28, 108, 122); margin-bottom: 10px; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.5); border-radius: 3px; box-shadow: 0px 1px 6px 4px rgba(0, 0, 0, 0.07) inset, 0px 0px 0px 3px rgb(254, 254, 254), 0px 5px 3px 3px rgb(210, 210, 210); transition: all 0.2s linear; } #wrapper p.button input:hover{ background: rgb(74, 179, 198); } #wrapper p.button input:active, #wrapper p.button input:focus{ background: rgb(40, 137, 154); position: relative; top: 1px; border: 1px solid rgb(12, 76, 87); box-shadow: 0px 1px 6px 4px rgba(0, 0, 0, 0.2) inset; } p.login.button, p.signin.button{ text-align: right; margin: 5px 0; }

Трюк заключается в том, чтобы использовать box-shadow, чтобы создать несколько рамок. Естественно, вы можете использовать лишь одну рамку, но также можно и несколько. Мы будем использовать параметр length для создания “фейковой” второй белой рамки, 3px в ширину, без размытия.

Теперь стилизуем чекбокс, здесь мы ничего необычного не сотворим:

/* стилизуем чекбокс "запомнить меня"*/ .keeplogin{ margin-top: -5px; } .keeplogin input, .keeplogin label{ display: inline-block; font-size: 12px; font-style: italic; } .keeplogin input#loginkeeping{ margin-right: 5px; } .keeplogin label{ width: 80%; }

Стилизуем подвал формы, используя множественные линейные градиенты, чтобы создать полосатый градиент.

P.change_link{ position: absolute; color: rgb(127, 124, 124); left: 0px; height: 20px; width: 440px; padding: 17px 30px 20px 30px; font-size: 16px ; text-align: right; border-top: 1px solid rgb(219, 229, 232); border-radius: 0 0 5px 5px; background: rgb(225, 234, 235); background: repeating-linear-gradient(-45deg, rgb(247, 247, 247) , rgb(247, 247, 247) 15px, rgb(225, 234, 235) 15px, rgb(225, 234, 235) 30px, rgb(247, 247, 247) 30px); } #wrapper p.change_link a { display: inline-block; font-weight: bold; background: rgb(247, 248, 241); padding: 2px 6px; color: rgb(29, 162, 193); margin-left: 10px; text-decoration: none; border-radius: 4px; border: 1px solid rgb(203, 213, 214); transition: all 0.4s linear; } #wrapper p.change_link a:hover { color: rgb(57, 191, 215); background: rgb(247, 247, 247); border: 1px solid rgb(74, 179, 198); } #wrapper p.change_link a:active{ position: relative; top: 1px; }

Сейчас вы видите, что у нас две приятные формы, но ведь мы хотим, чтобы отображалась только лишь одна из них. Пришло время анимации!

Создаем анимацию Первое, что мы сделаем, мы спрячем вторую форму, назначив opacity на 0:

#register{ z-index: 21; opacity: 0; }

Помните, что форма входа имеет параметр z-index: 22? Второй форме мы назначим этот параметр на 21, чтобы поставить его “под” форму входа.

Теперь самое интересное: меняем формы местами, используя псевдо класс:target. Вам нужно понять одну вещь по поводу:target: для перемещения мы будем использовать якоря. Нормальное поведение якоря - прыжок на определенный элемент страницы. Но мы не хотим этого, мы лишь хотим поменять формы местами. И тут приходит на помощь наш трюк с использованием двух ссылок в начале страницы. Вместо того, чтобы направить нас прямо на вторую форму, рискуя испытать эффект “прыжка”, мы придадим ссылкам параметр display: none . Это поможет избежать прыжков. Я обнаружил этот трюк на сайте: CSS3 create (французский язык).

#toregister:target ~ #wrapper #register, #tologin:target ~ #wrapper #login{ z-index: 22; animation-name: fadeInLeft; animation-delay: .1s; }

Вот, что происходит: когда мы кликаем на кнопку Присоединиться , мы направляемся на #toregister. Затем происходит анимация и лишь потом переходим на элемент #register. Мы используем анимацию под названием fadeInLeft . Так как мы “прячем” форму, используя нулевую прозрачность, мы применим анимацию, которая будем постепенно появляться. Мы также изменили z-index, чтобы она появилась поверх другой формы. То же самое происходит для другой формы same happens for the other form.
Вот код для анимации. Мы использовали CSS3 animation framework от Dan Eden и адаптировали этот фреймворк под наш туториал.

Animate{ animation-duration: 0.5s; animation-timing-function: ease; animation-fill-mode: both; } @keyframes fadeInLeft { 0% { opacity: 0; transform: translateX(-20px); } 100% { opacity: 1; transform: translateX(0); } }

Форма, которая “исчезает”, будет иметь анимацию затемнения влево:

#toregister:target ~ #wrapper #login, #tologin:target ~ #wrapper #register{ animation-name: fadeOutLeftBig; } @keyframes fadeOutLeft { 0% { opacity: 1; transform: translateX(0); } 100% { opacity: 0; transform: translateX(-20px); } }

Теперь вы можете использовать другие анимации от Dan Eden’ с помощью файла animate.css: просто измените класс.animate class и названия анимаций. Вы также обнаружите несколько других анимаций в конце файла animate-custom.css file.

Вот и все, друзья. Надеюсь вам понравился этот туториал!

Заметим, что в некоторых браузерах параметр background-clip: text не поддерживается. В Internet Explorer 9 анимации не работают. В Internet Explorer 8 и ниже псевдо-класс:target pseudo-class не поддерживается, поэтому там этот эффект вообще работать не будет.

P.S. Все замечания по поводу перевода с удовольствием приму в личку. Спасибо!

Теги: Добавить метки

Here is an example of html login page code. In this example, we have displayed one text field, Password, Reset button and Login button. We have used Reset button that resets all fields to blank.We have used JavaScript validation in Login page. We have set username and password value.

Here is an example of html login page code. In this example, we have displayed one text field, Password, Reset button and Login button. We have used Reset button that resets all fields to blank.We have used JavaScript validation in Login page. We have set username and password value.

Here is an example of html login page code. In this example, we have displayed one text field, Password, Reset button and Login button. We have used Reset button that resets all fields to blank. We have used JavaScript validation in Login page. We have set username and password value. If a person enter a wrong username or password or both, an error message with "Error: Incorrect Username or Password" will be displayed. Till the person enters the correct username and password, it will not Login.

Once you enter the correct Username and Password, you will be redirected to another page.

Login page is used in most of the dynamic website to validate user based on their credentials. For making login page for websites HTML form and HTML elements are used. Text field is used to accept username and password text field is used to accept password from user.

The submit button is used for submitting data to server for validation. Its good to validate user input in the browser using JavaScript. In this tutorial we are creating a HTML Login page code and validating user input with JavaScript. In modern web application server-side validation is also very important it is done on server side with the program running on the server.

Here is video tutorial:

But in this tutorial you will learn to create a login page in HTML and validate user input with JavaScript. View demo of HTML Login page .

Here is the screen shot of the the login page we are making:

This login page displays Username, Password text fields and then buttons for reset and Login. Once user enters the data and clicks on the Login button, JavaScript is used to validate the form and error message is displayed if validation fails.

HTML Login page with JavaScript Validation

Login Page

HTML Login Page
Username:
Password:
function check(form) { if(form.userid.value == "Roseindia" && form.pwd.value == "Roseindia") { return true; } else { alert("Error Password or Username") return false; } }

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

Первое поле – для логина, второе – для пароля. И вот со вторым не все так просто. Поскольку на текущий момент оно представляет собой просто поле для ввода текста.

Логин
Пароль

Результат в браузере:

Чтобы введенный в нем текст заменялся на звездочки, как это принято для поля такого типа, необходимо сделать одно простое действие. А именно, осуществить замену значения атрибута type на password :

Результат:

Кнопка отправки формы

Ну, вот. Наша форма уже почти готова. Теперь, чтобы завершить ее создание, необходимо сделать кнопку, которой будет осуществляться отправка формы. Задача решается с применением тега с типом submit .

Если на кнопке должна присутствовать какая-то надпись, то ее можно сделать, используя атрибут value . Задавать имя кнопке или нет – на ваше усмотрение, то если вы это сделаете, то сервер будет получать это имя, а также значение кнопки.

Как правило, в имени кнопки отправки формы есть потребность тогда, когда у формы есть несколько кнопок, каждая из которых выполняет определенное действие. Благодаря этому сервер, получая от браузера имя и значение кнопки, понимает, на какую именно кнопку нажал пользователь и что, соответственно, необходимо выполнить.

В итоге код нашей формы получится следующим:

Логин
Пароль

Результат в браузере:

A tutorial on how to create a switching login and registration form with HTML5 and CSS3.

In this tutorial we are going to create two HTML5 forms that will switch between login and registration using the CSS3 pseudo class :target . We will style it using CSS3 and an icon font. The idea behind this demo is to show the user the login form and provide a link to “switch” to the registration form.

Note that this is for demo purpose only, it will only work in browser supporting the:target pseudo class, and you should not use this code on a live website without providing solid fallback.

In the following, we will be going through Demo 1.

The HTML

In the HTML, we will put both forms, hiding the second one with CSS. Here is the code, I’ll explain some of the interesting parts later.

Log in

Your email or username

Your password

Keep me logged in

Sign up

Your username

Your email

Your password

Please confirm your password

We’ve added some HTML5 goodness here and used some of the new inputs. The input type=password automatically hides what the user is typing and replaces it with dots (depending on browser). The input type=email enables the browser to check if what the user entered has the format of a valid email address. We’ve also used the require=required attribute; browsers that support this attribute will not let the user submit the form until this field is filled, no JavaScript required.
The autocomplete=on attribute will prefill values based on earlier user input. We also used some nice placeholders for the inputs that will show some guiding value when the input is not filled.

Now the two tricky parts. You might have noticed the two links at the top of the form. This is a little trick that will make our form behave nicely when playing with anchors, so that it won’t “jump” on long pages when we click on the switching link and trigger the:target pseudo-class.

The second little trick is related to the use of the icon font. We will be using a data-attribute to display the icons. By setting data-icon=”icon_character” with the according character in the HTML we will just need one CSS attribute selector to style all the icons. Read more about this technique on 24 Ways: Displaying Icons with Fonts and Data- Attributes .

The CSS

For the clearness of the code in this tutorial, I will omit all the vendor prefixes, but you will, of course, find them in the files. Once again, I’m using some pretty advanced CSS3 tricks that might not work in all browsers. Let’s get started.

Styling both forms using CSS3

First, let’s give our two forms some general styling for the container.

#subscribe, #login{ position: absolute; top: 0px; width: 88%; padding: 18px 6% 60px 6%; margin: 0 0 35px 0; background: rgb(247, 247, 247); border: 1px solid rgba(147, 184, 189,0.8); box-shadow: 0pt 2px 5px rgba(105, 108, 109, 0.7), 0px 0px 8px 5px rgba(208, 223, 226, 0.4) inset; border-radius: 5px; } #login{ z-index: 22; }

We’ve added a nice box shadow that’s made of two shadows: an inset one to create the inner blue glow, and an outside shadow. We’ll explain the z-index in a bit.

In the following we will style the header with some background clipping:

/**** general text styling ****/ #wrapper h1{ font-size: 48px; color: rgb(6, 106, 117); padding: 2px 0 10px 0; font-family: "FranchiseRegular","Arial Narrow",Arial,sans-serif; font-weight: bold; text-align: center; padding-bottom: 30px; } /** For the moment only webkit supports the background-clip:text; */ #wrapper h1{ background: -webkit-repeating-linear-gradient(-45deg, rgb(18, 83, 93) , rgb(18, 83, 93) 20px, rgb(64, 111, 118) 20px, rgb(64, 111, 118) 40px, rgb(18, 83, 93) 40px); -webkit-text-fill-color: transparent; -webkit-background-clip: text; } #wrapper h1:after{ content:" "; display:block; width:100%; height:2px; margin-top:10px; background: linear-gradient(left, rgba(147,184,189,0) 0%, rgba(147,184,189,0.8) 20%, rgba(147,184,189,1) 53%, rgba(147,184,189,0.8) 79%, rgba(147,184,189,0) 100%); }

Note that at this moment only webkit browsers support background-clip: text , so we will create a stripped background only for webkit here, and clip it to the text to add the stripes to the H1 title. Since the background-clip: text property currently only works in Webkit browsers, I decided to go only with the webkit prefix. That’s the reason why I split the CSS declaration into two parts, and use a webkit prefixed gradient only. Only using the –webkit- prefix is bad practice, it’s only for demo purpose, and you should never do this on real a website! That’s also where the -webkit-text-fill-color: transparent comes in handy: it enables us to only have a transparent background on the webkit browsers, all the other ones will ignore it and give us the provided text color fallback.

We also created a fading line under the title with the help of the:after pseudo-class. We use a 2px height gradient and fade the background to 0 opacity at both ends.

Now let’s style our inputs and give them a nicer look.

/**** advanced input styling ****/ /* placeholder */ ::-webkit-input-placeholder { color: rgb(190, 188, 188); font-style: italic; } input:-moz-placeholder, textarea:-moz-placeholder{ color: rgb(190, 188, 188); font-style: italic; } input { outline: none; }

First we style the inputs, and remove the outline. But be careful here; the outline helps the user know which input is focused, so if you remove it, you should provide some:active and:focus states for the inputs.

/* all the input except submit and checkbox */ #wrapper input:not(){ width: 92%; margin-top: 4px; padding: 10px 5px 10px 32px; border: 1px solid rgb(178, 178, 178); box-sizing: content-box; border-radius: 3px; box-shadow: 0px 1px 4px 0px rgba(168, 168, 168, 0.6) inset; transition: all 0.2s linear; } #wrapper input:not():active, #wrapper input:not():focus{ border: 1px solid rgba(91, 90, 90, 0.7); background: rgba(238, 236, 240, 0.2); box-shadow: 0px 1px 4px 0px rgba(168, 168, 168, 0.9) inset; }

Here we used the:not pseudo class, to style all inputs, except the checkbox. I provided a:focus and:active state, since I decided to remove the outline.

And now the fun part: the icon font. Since we can’t use:before and:after pseudo classes on inputs, we’ll have to cheat a little bit: we’ll add the icon to the label, and then place it in the input. I’m using the fontomas library which puts together some nice icons. You can rearrange them to set the icon to a specific letter. Remember the data-icon attribute? It’s where you should put the letter. I used data-icon=’u’ for user, ‘e’ for email, ‘p’ for password. Once I chose the letters, I downloaded the font, and used the fontsquirrel font generator to transform it into a @font-face compatible format.

@font-face { font-family: "FontomasCustomRegular"; src: url("fonts/fontomas-webfont.eot"); src: url("fonts/fontomas-webfont.eot?#iefix") format("embedded-opentype"), url("fonts/fontomas-webfont.woff") format("woff"), url("fonts/fontomas-webfont.ttf") format("truetype"), url("fonts/fontomas-webfont.svg#FontomasCustomRegular") format("svg"); font-weight: normal; font-style: normal; } /** the magic icon trick ! **/ :after { content: attr(data-icon); font-family: "FontomasCustomRegular"; color: rgb(106, 159, 171); position: absolute; left: 10px; top: 35px; width: 30px; }

Yeah, that’s it folks, you don’t need to have a class for each icon. We used content: attr(data-icon) to retrieve the letter from the data-icon attribute, so we only have to declare the font, choose a nice color and position it.

Now let’s style the submit button for both forms.

/*styling both submit buttons */ #wrapper p.button input{ width: 30%; cursor: pointer; background: rgb(61, 157, 179); padding: 8px 5px; font-family: "BebasNeueRegular","Arial Narrow",Arial,sans-serif; color: #fff; font-size: 24px; border: 1px solid rgb(28, 108, 122); margin-bottom: 10px; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.5); border-radius: 3px; box-shadow: 0px 1px 6px 4px rgba(0, 0, 0, 0.07) inset, 0px 0px 0px 3px rgb(254, 254, 254), 0px 5px 3px 3px rgb(210, 210, 210); transition: all 0.2s linear; } #wrapper p.button input:hover{ background: rgb(74, 179, 198); } #wrapper p.button input:active, #wrapper p.button input:focus{ background: rgb(40, 137, 154); position: relative; top: 1px; border: 1px solid rgb(12, 76, 87); box-shadow: 0px 1px 6px 4px rgba(0, 0, 0, 0.2) inset; } p.login.button, p.signin.button{ text-align: right; margin: 5px 0; }

The trick here is to use the box-shadow in order to create some extra borders. You can only use one border, but as many box-shadows as you want. We will use the length value to create a “fake” second white border, 3px wide, with no blur.

Then we’ll style the checkbox, nothing very special here:

/* styling the checkbox "keep me logged in"*/ .keeplogin{ margin-top: -5px; } .keeplogin input, .keeplogin label{ display: inline-block; font-size: 12px; font-style: italic; } .keeplogin input#loginkeeping{ margin-right: 5px; } .keeplogin label{ width: 80%; }

We will style the bottom of the form using repeating linear gradients to create a striped background.

P.change_link{ position: absolute; color: rgb(127, 124, 124); left: 0px; height: 20px; width: 440px; padding: 17px 30px 20px 30px; font-size: 16px ; text-align: right; border-top: 1px solid rgb(219, 229, 232); border-radius: 0 0 5px 5px; background: rgb(225, 234, 235); background: repeating-linear-gradient(-45deg, rgb(247, 247, 247) , rgb(247, 247, 247) 15px, rgb(225, 234, 235) 15px, rgb(225, 234, 235) 30px, rgb(247, 247, 247) 30px); } #wrapper p.change_link a { display: inline-block; font-weight: bold; background: rgb(247, 248, 241); padding: 2px 6px; color: rgb(29, 162, 193); margin-left: 10px; text-decoration: none; border-radius: 4px; border: 1px solid rgb(203, 213, 214); transition: all 0.4s linear; } #wrapper p.change_link a:hover { color: rgb(57, 191, 215); background: rgb(247, 247, 247); border: 1px solid rgb(74, 179, 198); } #wrapper p.change_link a:active{ position: relative; top: 1px; }

Now you’ll notice that we’ve got two nice forms, but we really want only one to show at a time. So now is time for some animations!!

Creating the switching animation

The first thing to do is to hide the second form by setting the opacity to 0:

#register{ z-index: 21; opacity: 0; }

Remember that our login form had a z-index of 22? We will give the second form a z-index of 21, to put it “under” the login form.

And now the really good part: switching the forms using the:target pseudo class. What you really have to understand about:target, is that we will use anchors to make the transition. The normal behavior of an anchor link, is to jump to the target in the page. But we don’t want to jump anywhere, we only want to switch the forms. And here comes our trick using the two links at the top of the page. Instead of directly linking to the second form, and risking getting a “jumping” effect, we actually put the two links at the top of the page and give them display: none . This will avoid any page jump. Credit where credit’s due: I found this trick on CSS3 create (in French).

#toregister:target ~ #wrapper #register, #tologin:target ~ #wrapper #login{ z-index: 22; animation-name: fadeInLeft; animation-delay: .1s; }

So this is what happens: when we click on the Join us button, we trigger the #toregister. We then do the animation, by using the sibling selector ~ to find our #register element. We use an animation called fadeInLeft . Since we “hide” the form using zero opacity, we will use an animation that fades in, to make it appear. We’ve also changed the z-index, to make it appear on top of the other form.
The same happens for the other form.

And here is the code for the animation. We are using the CSS3 animation framework from Dan Eden and adapted it for this tutorial.

Animate{ animation-duration: 0.5s; animation-timing-function: ease; animation-fill-mode: both; } @keyframes fadeInLeft { 0% { opacity: 0; transform: translateX(-20px); } 100% { opacity: 1; transform: translateX(0); } }

The form that is “disappearing” will have another animation which will make it fade out to the left:

#toregister:target ~ #wrapper #login, #tologin:target ~ #wrapper #register{ animation-name: fadeOutLeftBig; } @keyframes fadeOutLeft { 0% { opacity: 1; transform: translateX(0); } 100% { opacity: 0; transform: translateX(-20px); } }

You can now use other animations from Dan Eden’s animate.css: just adjust your .animate class and replace the animation names. You will also find some custom animations at the end of the animate-custom.css file.

Well, that’s it folks. I hope you enjoyed the tutorial!

Please note, that in some browsers background-clip: text is not supported. In Internet Explorer 9 the transitions and animations don’t work, so there will be no fancy form switching. In Internet Explorer 8 and below the:target pseudo-class is not supported, so it won’t work at all (you’ll just see the login form).

HTML формы — сложные элементы интерфейса. Они включают в себя разные функциональные элементы: поля ввода и , списки , подсказки и т.д. Весь код формы заключается в элемент .

Большая часть информации веб-форм передаётся с помощью элемента . Для ввода одной строки текста применяется элемент , для нескольких строк - элемент . Элемент создает выпадающий список.

Элемент создаёт надписи к полям формы. Существует два способа группировки надписи и поля. Если поле находится внутри элемента , то атрибут for указывать не нужно.

Last Name Last Name Last Name

Поля формы можно разделять на логические блоки с помощью элемента . Каждому разделу можно присвоить название с помощью элемента .

Контактная информация Имя E-mail
Рис. 1. Группировка полей формы

Чтобы сделать форму более понятной для пользователей, в поля формы добавляют текст, содержащий пример вводимых данных. Такой текст называется подстановочным и создаётся с помощью атрибута placeholder .

Обязательные для заполнения поля также необходимо выделять. До появления HTML5 использовался символ звездочки * , установленный возле названия поля. В новой спецификации появился специальный атрибут required , который позволяет отметить обязательное поле на уровне разметки. Этот атрибут дает указание браузеру (при условии, что тот поддерживает HTML5), указание не отправлять данные после нажатия пользователем кнопки отправить, пока указанные поля не заполнены.

Для изменения внешний вид текстового поля при получении фокуса, используется псевдокласс focus . Например, можно сделать фон текущего поля более темным или добавить цветную рамку, чтобы оно выделялось среди остальных:

Input:focus { background: #eaeaea; }

Ещё один полезный html5-атрибут — атрибут autofocus . Он позволяет автоматически установить фокус на нужном начальном поле для элементов и (только в один элемент каждой формы).

Пример создания формы регистрации

HTML разметка

Регистрация Имя Пол мужской женский E-mail Страна Выберите страну проживания Россия Украина Беларусь Отправить

Примечание
action="form.php" — ссылка на файл обработчика формы. Создайте файл в кодировке UTF-8, закачайте его на сервер и замените action="form.php" на путь к файлу на вашем сервере.


Рис. 2. Внешний вид формы по умолчанию

Как видно из рисунка, каждый элемент формы имеет стили браузера по умолчанию. Очистим стили и оформим элементы формы.

Form-wrap { width: 550px; background: #ffd500; border-radius: 20px; } .form-wrap *{transition: .1s linear} .profile { width: 240px; float: left; text-align: center; padding: 30px; } form { background: white; float: left; width: calc(100% - 240px); padding: 30px; border-radius: 0 20px 20px 0; color: #7b7b7b; } .form-wrap:after, form div:after { content: ""; display: table; clear: both; } form div { margin-bottom: 15px; position: relative; } h1 { font-size: 24px; font-weight: 400; position: relative; margin-top: 50px; } h1:after { content: "\f138"; font-size: 40px; font-family: FontAwesome; position: absolute; top: 50px; left: 50%; transform: translateX(-50%); } /********************** стилизация элементов формы **********************/ label, span { display: block; font-size: 14px; margin-bottom: 8px; } input, input { border-width: 0; outline: none; margin: 0; width: 100%; padding: 10px 15px; background: #e6e6e6; } input:focus, input:focus { box-shadow: inset 0 0 0 2px rgba(0,0,0,.2); } .radio label { position: relative; padding-left: 50px; cursor: pointer; width: 50%; float: left; line-height: 40px; } .radio input { position: absolute; opacity: 0; } .radio-control { position: absolute; top: 0; left: 0; height: 40px; width: 40px; background: #e6e6e6; border-radius: 50%; text-align: center; } .male:before { content: "\f222"; font-family: FontAwesome; font-weight: bold; } .female:before { content: "\f221"; font-family: FontAwesome; font-weight: bold; } .radio label:hover input ~ .radio-control, .radiol input:focus ~ .radio-control { box-shadow: inset 0 0 0 2px rgba(0,0,0,.2); } .radio input:checked ~ .radio-control { color: red; } select { width: 100%; cursor: pointer; padding: 10px 15px; outline: 0; border: 0; background: #e6e6e6; color: #7b7b7b; -webkit-appearance: none; /*убираем галочку в webkit-браузерах*/ -moz-appearance: none; /*убираем галочку в Mozilla Firefox*/ } select::-ms-expand { display: none; /*убираем галочку в IE*/ } .select-arrow { position: absolute; top: 38px; right: 15px; width: 0; height: 0; pointer-events: none; /*активизируем показ списка при нажатии на стрелку*/ border-style: solid; border-width: 8px 5px 0 5px; border-color: #7b7b7b transparent transparent transparent; } button { padding: 10px 0; border-width: 0; display: block; width: 120px; margin: 25px auto 0; background: #60e6c5; color: white; font-size: 14px; outline: none; text-transform: uppercase; } /********************** добавляем форме адаптивность **********************/ @media (max-width: 600px) { .form-wrap {margin: 20px auto; max-width: 550px; width:100%;} .profile, form {float: none; width: 100%;} h1 {margin-top: auto; padding-bottom: 50px;} form {border-radius: 0 0 20px 20px;} }

Файл form.php

Примечание
В переменной $subject укажите текст, который будет отображаться как заголовок письма;
Ваше_имя — здесь вы можете указать имя, которое будет отображаться в поле «от кого письмо» ;
url_вашего_сайта замените на адрес сайта с формой регистрации;
ваш_email замените на ваш адрес электронной почты;
$headers .= "Bcc: ваш_email". "\r\n"; отправляет скрытую копию на ваш адрес электронной почты.