Контакти

Створення HTML форм. HTML-форми Який вибрати стиль сторінки авторизації

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

У цьому розділі ви збираєтеся створити дві HTML5 форми, які будуть переміщуватися між login і registration за допомогою CSS3 pseudo class :target . Ми повинні використовувати CSS3 і значок font. The idea behind this demo is to show the user the login form і надає link to “switch” to the registration form.

Зверніть увагу, що це є для демо purpose тільки, це буде тільки робота в браузері, сприяючи: target pseudo class, і ви не повинні використовувати цей код на живому веб-сайті без solid fallback.

In the following, we will be going через Demo 1.

The HTML

У HTML, ми повинні брати до себе форми, показуючи другу одну з CSS. Here is the code, I'll explain some of the interesting parts later.

Log in

Sign up

We’ve added some HTML5 хороша вона і використана деяка кількість нових вхід. The input type=passwordавтоматично викидає те, що user typing and replaces it with dots (depending on browser). The input type=email enable the browser to check if what the user entered has format of a valid email address. We’ve also used the require=required attribute; browsers що підтримує цей atribut не буде літа користувача, який застосовується до форми цілісного цього поля, невикористовується, а JavaScript не вимагається.
The autocomplete=on attribute буде попереднього значення, що базується на earlier user input. We also used some nice placeholders for 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. Це є короткий трік, що буде робити свою форму добре, якщо грати з мішками, так, що це “шump” на довгих сторінках, коли ми клацніть на лінію пересування, а також trigger the:target pseudo-class.

Second little trick is related to use of icon font. We will be using a data-attribute to display the icons. By setting data-icon=”icon_character” with the according character in HTML we will just need one CSS attribute selector to style all the icons. Докладніше про це технологія на 24 Ways: Displaying Icons with Fonts and Data- Attributes .

The CSS

Для вичерпування code в цій літературі, я повинен оминути всі орієнтири, але ви будете, курс, йти в них. 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 наші дві форми деякі загальні 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: 1p rgba(147, 184, 189,0.8); ; ) #login( z-index: 22; )

We've added a nice box shadow that's made of 2 shadows: an inset one to create the inner blue glow, an outside shadow. We'll explain з 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 moment only webkitsupports */ #wrapper h1( background: -webkit-repeating-linear-gradient(-45deg, rgb(18, 83, 93) , rgb(18, 83, 93) 20px, rgb(64, 111, 118) 20px, (64, 111, 118) 40px, rgb(18, 83, 93) 40px);-webkit-text-fill-color: transparent; "; display:block; width:100%; height:2px; margin-top:10px; ,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, Так що будуть створені stripped background тільки для webkit тут, і клацніть його до тексту до add stripes to H1 title. Since the background-clip: textВластивості поточно тільки робіт в Webkit браузерах, я вирішив, що ти тільки з webkit prefix. Те, що reason why I split the CSS declaration в дві частини, і використовувати 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Пройти в handy: він здатний до того, щоб тільки transparentі background on webkit браузери, всі інші ones буде ignore it і дбати, що виконаний текст бар'єр fallback.

We also created a fading line under the title with help of the:after pseudo-class. Використовуйте 2px сильний gradient і зніміть до 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; )

Вперше ми бачимо вхідні, і переміщуємо outline. But be careful here; outline helps the user know which input is focused, so if you remove it, ви повинні повідомити деякі:активні і:фокуси статей 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; 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 0 168, 168, 168, 0.9) inset;

Тут ми використовуємо:не pseudo class, to style all inputs, except the checkbox. Я надійшов на:фокус і:активний стан, нескінченно я вирішив перейти до outline.

And now the fun part: the icon font. Для того, щоб скористатися використанням:беззастережно і:поза pseudo classes on inputs, ми повинні cheat a little bit: ми клацніть на значок до мітки, і place it in the input. I'm using the fontomas library які puts together some nice icons. Ви можете rearrange them to set icon на 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. Після того, як роздруковують сторінки, я завантажив font, і використовує fontsquirrel font generator для перетворення його в @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 потрібно, щоб мати клас для кожної icon. We used content: attr(data-icon)натиснути напис від data-icon attribute, так що буде тільки вказати font, вибрати хороший колір і позицію його.

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; 0, 0, 0.5), border-radius: 3px; rgb(210, 210, 210); transition: all 0.2s linear; ) #wrapper p.button input:hover( background: rgb(74, 179, 198); ) .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 r 0, 0, 0.2) inset;) p.login.button, p.signin.button( text-align: right; margin: 5px 0; )

Трік тут є використання box-shadow в порядку для створення деяких extra borders. Ви можете тільки використовувати один ліхтарик, але як багато 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 "натисніть мені""/ .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%; )

Ви будете стилю внизу форми використання repeating linear gradients для створення striped background.

P.change_link( position: absolute; color: rgb(127, 124, 124); left: 0px; border-top: 1px solid rgb(219, 229, 232); border-radius: 0 0 5px 5px; background: rgb(225, 234, 235); 247, 247) rgb(247, 247, 247) 15px, rgb(225, 234, 235) 15px, rgb(225, 234, 235) 30px, rgb(247, 2) .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 ); background: rgb(247, 247, 247); border: 1px solid rgb(74, 179, 198);

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

Creating the switching animation

Перший, щоб зробити, щоб вийти на дві форми, щоб встановити оpacity до 0:

#register(z-index: 21; opacity: 0; )

Remember that our login form had з-index 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. Normal behavior of anchor link, is to jump to the target in the page. Але ми не будемо йти на ходу будь-де, ми тільки хотіли б перетворювати форми. And here comes our trick using the two links at the top of the page. Натисніть на прямому зв'язку до другої форми, і зростаючий, щоб зробити “jumping” ефект, we actually put the two links at the top of the page and give them display: none. Це буде avoid any page jump. Credit where credit’s due: Я вивів цей трюк на 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. Будьте до animation, використовуючи симулятор selector ~ до find our #register element. We use an animation called fadeInLeft. Since we “hide” form using zero opacity, we will use an animation that fades in, to make it appear. We’ve also змінюється z-index, щоб зробити це з'ясувати на верхній частині іншої форми.
Ті самі happens for інші форми.

And here is the code for the animation. Ви можете використовувати CSS3 animation framework з Dan Eden і 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); ) )

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); ) )

Ви можете використовувати інші animations від Dan Eden's animate.css: just adjust your .animate class and replace the animation names. Ви будете find деякі custom animations at end of the animate-custom.css файл.

Well, що це folks. I hope you enjoyed the tutorial!

Please note, that in some browsers background-clip: text is not supported. У браузері Internet Explorer 9 трансляції та animations не працює, тому що не буде простий спосіб перемикання. В Internet Explorer 8 і нижче:target pseudo-class is not supported, so it won't work at all (you'll just see the login form).

Сама форма зазвичай призначена для отримання від користувача інформації для подальшого пересилання її на сервер, де ці форми приймає програма-обробник. Така програма може бути написана будь-якою серверною мовою програмування на кшталт PHP, Perl та ін. Адреса програми вказується в атрибуті action тега

, як показано у прикладі 1.

Приклад 1. Надсилання даних форми

HTML5 IE Cr Op Sa Fx

Дані форми



У цьому прикладі дані форми, позначені атрибутом name (login і password), будуть передані у файл за адресою /example/handler.php. Якщо атрибут action не вказувати, передача відбувається на адресу поточної сторінки.

Передача на сервер відбувається двома різними методами: GET і POST для завдання методу в тезі

використовується атрибут method, яке значеннями виступають ключові слова get і post. Якщо атрибут метод не заданий, то за умовчанням дані відправляються на сервер методом GET. У табл. 1 показано різницю між цими методами.

Який метод використовується легко визначити за адресним рядком браузера. Якщо в ній з'явився знак питання і адреса стала схожою на цю, то це точно GET.

http://www.google.ru/search?q=%D1%81%D0%B8%D1%81%D1%8C%D0%BA%D0%B8&ie=utf-8

Унікальне поєднання параметрів адресного рядка однозначно ідентифікує сторінку, тому сторінки з адресами?q=node/add і?q=node вважаються різними. Цю особливість використовують системи управління контентом (CMS, Content management system) для створення багатьох сторінок сайту. Насправді ж використовується один файл, який отримує запит GET і відповідно до нього формує вміст документа.

Нижче наведено типові області застосування цих методів на сайтах.

GET

Передача невеликих текстових даних на сервер; Пошук по сайту.

Пошукові системи, форми пошуку по сайту завжди відправляються методом GET, це дозволяє ділитися результатами пошуку з друзями, надсилати посилання поштою або викладати його на форумі.

POST

Пересилання файлів (фотографій, архівів, програм та ін.); відправлення коментарів; додавання та редагування повідомлень на форумі, блозі.

Робота з формою за промовчанням відбувається в поточній вкладці браузера, при цьому допустимо при відправленні форми змінити цей параметр і відкривати обробник форми у новій вкладці або у кадрі. Така поведінка задається через «ім'я контексту», яке є значенням атрибуту target тега . Популярні значення це _blank для відкриття форми в новому вікні або вкладці та ім'я кадру, яке задається атрибутом name тега



У цьому прикладі при натисканні на кнопку «Надіслати» результат відправки форми відкривається у кадрі з ім'ям area .

Елементи форми зазвичай розташовуються всередині тега

, тим самим визначаючи дані, які будуть передаватися на сервер. Водночас у HTML5 є можливість відокремити форму від її елементів. Це зроблено для зручності та універсальності, так, складний макет може містити кілька форм, які не повинні перетинатися між собою або, наприклад, деякі елементи виводяться за допомогою скриптів в одному місці сторінки, а сама форма знаходиться в іншому. Зв'язок між формою та її елементами відбувається у такому разі через ідентифікатор форми, а до елементів слід додати атрибут form зі значенням, що дорівнює цьому ідентифікатору (приклад 3).

Приклад 3. Зв'язування форми з полями

HTML5 IE Cr Op Sa Fx

Форма



У цьому прикладі тег

однозначно ототожнюється через ідентифікатор auth , а полям, які слід відправити за допомогою форми, додається form="auth" . При цьому поведінка елементів не змінюється, при натисканні на кнопку логін та пароль пересилаються на обробник handler.php.

Хоча параметри передачі форми традиційно вказуються в тезі , їх можна перенести і в кнопки відправлення форми (

Сподобалася стаття? Поділіться їй