Верстка формы поиска. Компактная форма поиска на CSS3 Форма поиска html5 css3

Поле поиска для сайта — один из важнейших элементов пользовательского интерфейса на веб-странице. С его помощью пользователь может найти нужный контент на вашем сайте.

В этом уроке вы узнаете, как создать разметку для поля поиска с помощью HTML5, а также как стилизовать элементы формы, используя возможности CSS3, без использования скриптов.

1. Разметка HTML

Элемент

является контейнером для формы поиска, поле поиска создается при помощи элемента или , а кнопка отправки данных на сервер может создаваться с помощью элемента или
* {box-sizing: border-box;} form { position: relative; width: 300px; margin: 0 auto; } input { width: 100%; height: 42px; padding-left: 10px; border: 2px solid #7BA7AB; border-radius: 5px; outline: none; background: #F9F0DA; color: #9E9C9C; } button { position: absolute; top: 0; right: 0px; width: 42px; height: 42px; border: none; background: #7BA7AB; border-radius: 0 5px 5px 0; cursor: pointer; } button:before { content: "\f002"; font-family: FontAwesome; font-size: 16px; color: #F9F0DA; }

3. Поле поиска с кнопкой внутри

* {box-sizing: border-box;} form { position: relative; width: 300px; margin: 0 auto; } input, button { border: none; outline: none; border-radius: 3px; } input { width: 100%; height: 42px; background: #F9F0DA; padding-left: 15px; } button { height: 26px; width: 26px; position: absolute; top: 8px; right: 8px; background: #F15B42; cursor: pointer; } button:before { content: "\f105"; font-family: FontAwesome; color: #F9F0DA; font-size: 20px; font-weight: bold; }

4. Поле поиска в стиле «flat»

* {box-sizing: border-box;} form { position: relative; width: 300px; margin: 0 auto; background: #A3D0C3; } input, button { border: none; outline: none; background: transparent; } input { width: 100%; height: 42px; padding-left: 15px; } button { height: 42px; width: 42px; position: absolute; top: 0; right: 0; cursor: pointer; } button:before { content: "\f002"; font-family: FontAwesome; font-size: 16px; color: #F9F0DA; }

5. Поле поиска с толстой нижней границей

* {box-sizing: border-box;} form { position: relative; width: 300px; margin: 0 auto; background: #F9F0DA; border-bottom: 4px solid #be290e; } input, button { border: none; outline: none; background: transparent; } input { width: 100%; height: 42px; padding-left: 15px; } button { height: 42px; width: 42px; position: absolute; top: 0; right: 0; cursor: pointer; } button:before { content: "\f178"; font-family: FontAwesome; font-size: 20px; color: #be290e; }

6. Поле поиска с меняющимся цветом границы

* {box-sizing: border-box;} form { position: relative; width: 300px; margin: 0 auto; } input, button { outline: none; background: transparent; } input { width: 100%; height: 42px; padding-left: 15px; border: 3px solid #F9F0DA; } button { border: none; height: 42px; width: 42px; position: absolute; top: 0; right: 0; cursor: pointer; } button:before { content: "\f002"; font-family: FontAwesome; font-size: 16px; color: #F9F0DA; } input:focus { border-color: #311c24; }

7. Выезжающее поле поиска

Поле поиска появляется при нажатии на кнопку с иконкой.

* {box-sizing: border-box;} form { position: relative; width: 300px; margin: 0 auto; height: 42px; } input { height: 42px; width: 0; padding: 0 42px 0 15px; border: none; border-bottom: 2px solid transparent; outline: none; background: transparent; transition: .4s cubic-bezier(0, 0.8, 0, 1); position: absolute; top: 0; right: 0; z-index: 2; } input:focus { width: 300px; z-index: 1; border-bottom: 2px solid #F9F0DA; } button { background: #683B4D; border: none; height: 42px; width: 42px; position: absolute; top: 0; right: 0; cursor: pointer; } button:before { content: "\f002"; font-family: FontAwesome; font-size: 16px; color: #F9F0DA; }

8. Увеличивающееся в ширину поле поиска

* {box-sizing: border-box;} form { width: auto; float: right; margin-right: 30px; } input { width: 250px; height: 42px; padding-left: 15px; border-radius: 42px; border: 2px solid #324b4e; background: #F9F0DA; outline: none; position: relative; transition: .3s linear; } input:focus { width: 300px; } button { width: 42px; height: 42px; background: none; border: none; position: absolute; top: -2px; right: 0; } button:before{ content: "\f002"; font-family: FontAwesome; color: #324b4e; }

Меня раскритиковали, мол верстка отстой, есть же современные HTML5 и CSS3.

Я, конечно, понимаю, последние стандарты это круто и все такое. Но дело в том, что верстаю я, как правило, под заказ, а там в большинстве случаев важна полная идентичность в разных браузерах, что не позволяет использовать последние технологии. Поэтому я ориентируюсь в первую очередь на кроссбраузерность и поисковую форму по привычке сверстал «по-старому».

В общем, этим постом исправляю ситуацию (в угоду недовольным прошлой статьей =) и предлагаю свой вариант верстки той же самой поисковой формы, но уже с использованием технологий HTML5 и CSS3.

Пример того, что получится в результате, можно .

Что мы теряем при верстке данной формы с помощью HTML5 и CSS3

  1. IE9 и ниже — не увидим текст по умолчанию (атрибут placeholder).
  2. IE8 и ниже — не увидим закругленных углов и внутренних теней.
  3. IE7 — для него приходится указать другую ширину формы, т.к. он не поддерживает свойство box-sizing .
  4. IE6 — а его вообще в расчет не берем =)

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

HTML-код формы поиска

Выглядит он вот так:

По сравнению с формой из предыдущей статьи здесь внесены следующее изменения в соответствии с технологией HTML5:

  1. Атрибут type="text" заменен type="search" .
  2. Инлайновый скрипт заменен на placeholder="поиск" .

CSS-код

Вот все необходимые стили с комментариями:

Search { /* устанавливаем необходимую ширину формы в зависимости от дизайна ** форма без проблем растягивается */ width: 35%; /* кнопку отправки будем позиционировать абсолютно, ** поэтому необходимо это свойство */ position: relative; } .search input { /* отключаем бордюры у инпутов */ border: none; } /* стили для поля ввода */ .search .input { /* растягиваем поле ввода на всю ширину формы */ width: 100%; /* за счет верхнего (8px) и нижнего (9px) внутренних отступов ** регулируем высоту формы ** внутренний отступ справа (37px) делаем больше левого, ** т.к. там будет размещена кнопка отправки */ padding: 8px 37px 9px 15px; /* чтобы ширина поля ввода (100%) включала в себя внутренние отступы */ -moz-box-sizing: border-box; box-sizing: border-box; /* добавляем внутренние тени */ box-shadow: inset 0 0 5px rgba(0,0,0,0.1), inset 0 1px 2px rgba(0,0,0,0.3); /* закругляем углы */ border-radius: 20px; background: #EEE; font: 13px Tahoma, Arial, sans-serif; color: #555; outline: none; } /* меняем оформление поля ввода при фокусе */ .search .input:focus { box-shadow: inset 0 0 5px rgba(0,0,0,0.2), inset 0 1px 2px rgba(0,0,0,0.4); background: #E8E8E8; color: #333; } /* оформляем кнопку отправки */ .search .submit { /* позиционируем кнопку абсолютно от правого края формы */ position: absolute; top: 0; right: 0; width: 37px; /* растягиваем кнопку на всю высоту формы */ height: 100%; cursor: pointer; background: url(https://lh4.googleusercontent.com/-b-5aBxcxarY/UAfFW9lVyjI/AAAAAAAABUg/gQtEXuPuIds/s13/go.png) 50% no-repeat; /* добавляем прозрачность кнопке отправки */ opacity: 0.5; } /* при наведении курсора меняем прозрачность кнопки отправки */ .search .submit:hover { opacity: 0.8; } /* данное свойство необходимо для того, чтобы в браузерах ** Chrome и Safari можно было стилизовать инпуты */ input { -webkit-appearance: none; }

И стили для IE ниже 9-й версии:

/* задаем отдельные стили для браузеров IE ниже 9-й версии */ *+html .search { /* для IE7 подгоняем ширину под другие браузеры и добавляем правый ** внутренний отступ, чтобы кнопка отправки встала на свое место */ width: 28%; padding: 0 52px 0 0; } .search .input { border: 1px solid #DFDFDF; border-top: 1px solid #B3B3B3; padding-top: 7px; padding-bottom: 8px; } .search .input:focus { border: 1px solid #CFCFCF; border-top: 1px solid #999; } .search .submit { filter: alpha(opacity=50); } .search .submit:hover { filter: alpha(opacity=80); }

P.S. Спасибо критикам за комментарии к предыдущей статье! Благодаря вам, у меня в голове отложились некоторые новые для меня моменты по верстке.

A search box is one of the prime components of website that define and enhance the User Interface of a website. Undoubtedly, a search form is a much needed component of a well-structured website to enhance its usability among the users. This basic user-interface element serves various purposes by helping the visitors to navigate through the website easily to exactly find what they are looking for.

Firstly, this one line search component is usually placed visibly on the navigation bar or sometime hidden under a regular icon that serves lots of advantages; also, it saves a lot of time, makes website user-friendly, improves navigation and user-experience. Finally, the icing on the cake is that it is very easy to create a search box.

If you are among the website owners who don’t have a search box on their website yet, or are looking for some better search forms to replace your original ones, then this listed tutorial of best search form scripts of CSS3, HTML, and jQuery might help in serving your purpose.

Before heading on to the list of the best tutorial/scripts of Bootstrap, CSS3, HTML5, and jQuery search forms, lets’s know why is search form so important in a website.

Glimpses to The Benefits of Search Form in a Website:

  1. Website becomes more interactive and user-friendly
  1. Enhances the user-experience
  1. Allows site-wide navigation
  1. Simplifies the search process by easily directing the user to the desired section
  1. Saves time and money

I have compiled a list of the best non-paid CSS3, HTML5, and jQuery search forms available online which can be used to easily create a search box from scratch.

Explore 2.5 Million Digital Assets including 2018’s Best WordPress Themes

2M+ items from the world’s largest marketplace for HTML5 Templates, Themes & Design Assets. Whether that’s what you need, or you’re just after a few Stock Photos – all of it can be found here at Envato Market.

DOWNLOAD NOW

Colorlib Search Form v1


We bring you a whopping collection of outstanding free search form examples which you can utilize for an assortment of different purposes. This particular one is ideal for travel-related websites as well as directories. With a full-screen image background, you can create an awesome atmosphere which translates into a pleasant searching experience. You can also fine-tune the form and make it follow your branding regulations without a sweat. Instead of creating one from scratch, you can now speed up the process and add this nifty city-first form to your web space. Head over to the live preview page and hit the download button afterward.

Colorlib Search Form v2


As a travel platform, you sure do want to offer your users solid search functions. If you focus primarily on hotels, this killer free search form will do you well. It has a fully flexible and responsive web design which instantly reshapes its structure to any device. Indeed, Colorlib Search Form v2 works on smartphones, tablets and desktops like a dream.

Moreover, the template also has date pickers, as well as an option to choose how many persons will be traveling. Implement it into your existing website and offer your visitors and potential customers something more. With appropriate search results, they can quickly book their trip and get the excitement going strong.

Colorlib Search Form v3


Colorlib Search Form v3 is a free search form example for someone who is running an online store. And if you utilize the default settings, Colorlib Search Form v3 is best for fashion and apparel eCommerce websites. Of course, you will have a breeze correcting the settings and making the template follow your rules and regulations precisely. It is a simple to use form which you can put into play without running into any issue at all. After all, Colorlib Search Form v3 is completely free of charge, ready and set for you to benefit you greatly. Get involved now and enjoy the results.

Colorlib Search Form v4


Are you in the process of bringing into being a banging online apparel shop? If that is the case and you are just adding the last finishing touches, spice things up with this free HTML5 search form example. Not only spice up, but speed up, too. After all, you now do not have to create a search form from scratch anymore. You have it all set up and ready to go, just a quick click away. You can even create a separate page which will be all about the search form with a full-screen image background. Right below the form, you can also list most searched keywords or link it to other sections and categories of your eCommerce website.

Colorlib Search Form v5


Beautiful and practical, those are the two main characteristics of Colorlib Search Form v5. This free search form template is stunningly flexible, perfect for someone who is on their mobile device, as well as for desktop users. Colorlib Search Form v5 has a bold with an image background which elevates the experience. You can get things moving forward right away, just hit the download button now and start introducing this awe-inspiring search template to your already jaw-dropping web shop. Bear in mind, although Colorlib Search Form v5 is simple to use, basic coding knowledge is necessary to be able to work with it successfully.

Colorlib Search Form v6


Colorlib Search Form v6 is another modern and sophisticated free search form template ideal for stores pushing fashion goods and accessories. Indeed, if you dig the layout but you would like to use it for something else, feel free to go entirely against the norm with it. Colorlib Search Form v6 features a rounded search bar with an option to add text above and bellow. The background image gives it an edge, making the search feature on your page more appealing to the eye. Of course, Colorlib Search Form v6 is also fully responsive and mobile-ready as you can see on the live preview page of the template.

Colorlib Search Form v7


If you are interested in adding a more advanced search form to your web platform, you better not miss checking out Colorlib Search Form v7. Along with the basic search function, there is also an advanced option which covers six different fields. Another cool feature of this free search form example is the delete button. It sets all the fields back to default so you do not have to clear them all manually. Very convenient indeed. There is also a results counter which shows how many items there are available for the particular keyword you are interested in.

Colorlib Search Form v8


Are you in need of even more free search form examples based on CSS3 and HTML5? If that is the case, well, keep on scrolling and enjoying all the amazing content that we bring to the table. Here is another fantastic solution for fashion stores with an advanced search function and image background. Similar to the previous template, this one also has a button which resets your search parameters back to default. Along with the main search bar, there are six additional fields to fill out and get the most accurate results possible. Also, the form has a nice dark finish to it which makes it more elegant.

Colorlib Search Form v9


Colorlib Search Form v9 is a multi-purpose free search form layout which you can utilize for an assortment of different aims. If you are running a web space with a ton of content and items going on, an advanced search function would come very handy. And that is something Colorlib Search Form v9 delivers. It has a professional and sophisticated look to it which you can effortlessly alter, making it follow your branding regulations precisely. But if you fancy it out of the box, by all means, use it as is and finish implementing it into your page in a snap of a finger.

Colorlib Search Form v10


A neat, contemporary and fully flexible free search form template with a gradient effect to spice things up a little bit. Not only will this tool easily set you apart from the competition and create a delightful experience, but it also comes with additional advanced search section. Along with the main search bar (with rounded edges), there are six extra fields with a drop-down option which you can modify according to your business preference. And to make repeating searches more comfortable, there is a reset button included in the layout, too. Do not forget to check Colorlib Search Form v10 out on mobile and see how well it reshapes its structure.

Colorlib Search Form v11


Hotels and other accommodation businesses, Colorlib Search Form v11 is a nifty and easy to use tool which will do you exceptionally well. Bear in mind, the design also works for flights, car rental and more. If you are building a page, layout by layout, block by block, you better save yourself time with predefined designs. This particular free search form template is packed with goodies that will get you going in little to no time. First thing’s first, it rocks an image background. Use it strategically and you will capture their attention in an instant. Moreover, Colorlib Search Form v11 also rocks all the necessary sections for a quick and comfortable search.

Colorlib Search Form v12


Another remarkable free search form template for hotels, flights and car rentals with a responsive and fully mobile-friendly layout. It comes with different options for quick searches, as well as date pickers for check-ins and check-outs. The form is equipped with a transparent gradient frame with an image background. If you would like to skip the basics and create a more modernistic look, you have the right solution right in front of your eyes. Just download it, after all, the template is entirely free of charge, ready and set for you to take it to your full advantage.

Colorlib Search Form v13


As a directory owner, you better have a neat, comfortable to use and resourceful search function available on your page for all your visitors. This way, they can quickly discover what they are interested in, completing the search, which is normally long and tedious, in a small breeze. For cities, bars, hotels, restaurants and other whatnots specifically, Colorlib Search Form v13 is the right option for you. It is entirely free of charge so you can easily download it and test it out and only later decide if it is a fit for your needs. Oh boy, will it be a perfect match with your banging online platform.

Colorlib Search Form v14


Keep things simple and to the point with Colorlib Search Form v14. If you are about to launch a fresh tourism website, you better make sure your search option is fully sorted out. This way, everyone can quickly find and book the right adventure for their upcoming vacation. With Colorlib Search Form v14, you can easily introduce a convenient search bar which will smoothly immerse itself into your existing web space. Round edges and shade effect make it appear very modern and trendy. Check-in and check-out date pickers, as well as the number of guests field, are integrated out of the box.

Colorlib Search Form v15


Beach vibes are going strong with this free search form template. With that in mind, you guessed it, Colorlib Search Form v15 is the best fit for everything travel and tourism-related. Searching for hotels, cars and flights has never been easier thanks to the easiness and sophistication this layout brings to the table. Enjoy leaving the layout exactly as is and attach it to your website for a super swift solution. But performing additional tweaks and improvements is possible, too. Along with the mandatory, Colorlib Search Form v15 also includes two check boxes to offer a customer even more options.

Colorlib Search Form v16


An awesome free search form example template for making browsing hotels, cars and flights a breeze. Needless to say, it is a tool best for making online bookings with two fields to state the destination, as well as departing and returning dates. Additionally, Colorlib Search Form v16 has three boxes to tick and image background. Of course, you can alter each section according to the main objective. Colorlib Search Form v16 also fluently adapts to different devices and appears stunningly on retina screens. Basic at first glance, but powerful and practical enough to get the job done in little to no time.

Colorlib Search Form v17


This particular template offers a three-in-one type of form where the user can choose between booking a hotel, a car or a flight. The filtering is done flawlessly for quick execution. Also, each section comes with a different set of fields, appropriate for the subject. All three include date pickers while only car section sports a time picker as well. Not to mention, you can customize Colorlib Search Form v17 to your likings, correct fields to your needs and offer all your visitors a convenient way of finding the best booking options for their needs and preferences. Either you implement this free search form layout to your page or use it as an individual page, both options work without a hitch.

Colorlib Search Form v18


Absolutely phenomenal free HTML5 search form template aka a form wizard which you will have a lot of fun implement into your web design. Colorlib Search Form v18 smoothly alters to all sorts of different website styles, for as long as they relate to travel and tourism. With the image background, you can strategically create a strong first impression, getting everyone intrigued in filling out the form as quickly as possible. Of course, you can introduce the form to one of your predefined layouts or use it exactly as is. Save time and effort and approach search forms for hotels, renting cars and flights cleverly.

Colorlib Search Form v19


Colorlib Search Form v19 is another free search form alternative perfect for flights and airlines. The form rocks a modern box with rounded edges and transparent, gradient effect. The background consists of an eye-catchy image which only lifts up the overall experience. As for the form, it rocks five different fields and a search button; from and to, passengers, depart and return. The latter two come with date pickers as well. If a decent search form is all your page is missing, you now know where to get one ready-made and entirely free of charge. Hit the download button and you are good to go.

Colorlib Search Form v20


Are you setting up an online hub where folks from all over the globe could quickly find their best flight deal? If that is the case, well, a solid search form is one of the mandatory functions that you need to rock on your website. Colorlib Search Form v20 is a banging free search form example which you can utilize exactly as is or use as an inspiration. It has nice attention to details with rounded edges and gradient and transparent effect. The background is also an image which establishes a wonderful atmosphere. Last but not least, the layout is 100% mobile-friendly, which you can also A-test by heading over to the live preview page.

Colorlib Search Form v21


If you would like to keep your online presence as simple and as minimal looking as possible, then you definitely need Colorlib Search Form v21. It comes as a button with a search icon which, when you click on it, opens an entire search bar. Furthermore, Colorlib Search Form v21 also comes in two different styles, round and square. Of course, this free search form works on mobile and desktop devices flawlessly, so responsiveness is something not to worry about. Simply download the tool now and get it to shine on your website sooner rather than later, offering a cool search option.

Colorlib Search Form v22


A modern, simple and sophisticated free search form layout which you can use for all and every website. From businesses and blogs to portfolios and online stores, Colorlib Search Form v22 adapts to all concepts out of the box. Also, this tool works great as an overlay search function, which keeps typing in characters completely distraction-free. No need to overcomplicate things when you have tons of predefined layouts and components always at your disposal. Not only that, but many premium-like items also do not cost you a dime. Well then, what are you waiting for, download the form now and get it to decorate your page. When function meets style – that’s what’s up when it comes to Colorlib Search Form v22.

Colorlib Search Form v23


Cleanness with a touch of creativity, that is what you get with Colorlib Search Form v23. It is a free search form template based on HTML5, fluently reshaping to smartphones, tablets and desktop computers. Along with the search bar and call-to-action button, you can also add different texts inside the search field itself, as well as right below it. You can also use an image background or keep things blank, whatever suits your needs best, Colorlib Search Form v23 handles a lot for a free tool. Now you know you do not need to start from the ground up anymore.

Colorlib Search Form v24


While some websites offer just to search by keyword, you can do more than that with Colorlib Search Form v24. It is a free search form template, which goes beyond the basic search function. As you can see, you can offer all your users to refine their search by choosing the right category from the drop-down field. They will find the exact item they are looking for even quicker now. A comfortable and quick search function and site navigability are great additions to a superb experience. Make sure a visitor leaves your online space satisfied and you with a new conversion.

Colorlib Search Form v25


While Colorlib Search Form v25 suits online apparel and accessory stores best, you can also go entirely against the norm and utilize it for something completely different. The options are very many once you have access to a versatile and flexible tool which happens to be super simple to use. Image background with shading, category drop-down field, search bar and a button with a gradient effect, that is basically it when it comes to Colorlib Search Form v25. Feel free to connect it to your page out of the box or fine-tune it further; regardless of your meticulous taste, this tool matches it undoubtedly.

It is a simple and centrally aligned search form with a text area (that glows when clicked) and a submit button. The animated glowing border of this search box makes it more attractive and interactive as it glows instantly whenever the text is entered in that box. Also, this styled box was developed with CSS and HTML, which is functional with jQuery. Get a closer look of the functions and designs of this search box in this tutorial.

Search box is a much needed and the most frequently used element in a website. This simple search tool makes your website beautiful and user-friendly. It enhances the user-experience by simplifying the navigation and exploration. All you need to do is just follow the guidelines as mentioned in the tutorial and create the search box from scratch on your own.

This classy search form is unique with its expandable feature(s). Primarily, only a search icon appears on the screen but on clicking that icon, the expanding search bar pops out. Not just this, it automatically moves back to its usual magnifying glass icon whenever the search bar is left empty. Further, checkout the tutorial to get a clear picture of the designing procedure of this CSS3 and HTML based search form.

Every visitor that lands on your website improves the ranking of your business, so now it’s your duty to enhance the experience of these users by providing a well-structured site-wide search option. Thereby, they can easily explore and navigate the site in fractions of time. This tutorial will give you a detailed look into the complete process of search tool designing with amazing designs and forms.

Learn step by step from this tutorial to get a stylish CSS3 Search Box on your website to attract more visitors on your website. These stylish and attractive search boxes help the users easily get what they are looking for on your website, which saves their time and creates a lasting good impression of your business & website on them.

Exact to its name, this search box “Loooong The Search Bar” expands automatically whenever the search area is clicked. Such an amazing search bar is created using CSS3 with no subsequent use of any scripting language. Hold back your visitors by serving them with functional elements like this. Still confused about the functions and features of this search form? No worries, get a look at the informative tutorial to know how to create a “Loooong The Search Bar” in your website.

Get styled search box integrated with special effects like transitions, round-corners, and box-shadows in just few simple steps mentioned in the tutorial. This all new creative search box comes with a predictive text feature in search fields. It shows all the archived, suggested, and the most proximate search results. It helps the users quickly search by just using the initials of keywords.

Once you enter the text by clicking on the magnifying glass icon of the webpage, it expands further in animated form. The appearance of the search bar changes from being simple to highly attractive and intuitive. You will understand it more clearly from the tutorial with detailed procedure to build an animated search from.

Firstly, this Apple inspired search box is created using CSS3 to satisfy the never-dying inclination of Apple users. Additionally, to personalize the search experience as same as an apple device, you can look up for this search bar tutorial to create on your own.

Clean Search Form, CSS3/jQuery + PSD

If you want to mark your website above the others, then you need to add unique elements into your website. A search box is one among it. If you have a customized search box, then surely it would be easier for a visitor to explore your website, which might turn your frequent visitors into prospective buyers. This search box is also built-in CSS3 having simplified jQuery validation with an interesting feature i.e a pop-up appears if the user misses to find and fill the search field.

Are you looking for some cool and inspiring search forms for your website? Then check out this tutorial to build amazing CSS3 search box using HTML5 and jQuery validation. Moreover, using the Modernizr’s feature, you can easily make your search box compatible with your browsers.

This eye-catching search form is unique in its look and display that accentuates the look of the website. The special layered effect down below the search box is also sure to attract visitors on the first go. Overall, checkout this tutorial to take a glance at the procedure of creating a search form from scratch.

Search Box with flexible attribute

This flexible search form contains flexible search input field with submit button of fixed-width and fixed-border. This awe-inspiring feature is sure to grab attention of the visitors when they land on your website. Also, get detailed information in this tutorial how functions and coding of CSS3 and HTML5 worked together.

It is an apt search form that compliments the structure of a website is always preferred by both developers and website owners. Based on the usage of a search form, it is equally important to do some styling changes in its structure and display. With a magnifying glass icon on the above and rounded search bar below, this kind of search bar looks great. Learn more from the tutorial.

Creating a flat style navigation bar with a search box and drop-down menu is now easy with this tutorial. You can add elements like settings, list, options by using HTML coding and with CSS, add basic styles, navigation and list items, links, search box, drop-down menu, etc. This drop-down menu falls vertically showing all the options available.

Thank you for visiting Colorlib and reading this article! We highly appreciate it! Now you might want to learn how to make a website

Disclosure: This page contains external affiliate links that may result in us receiving a commission if you choose to purchase mentioned product. The opinions on this page are our own and we don"t receive additional bonus for positive reviews.

В статье описаны особенности верстки поисковой формы сайта, приведен пример семантичной разметки кода, оформление на CSS3, плюс в конце немного магии jQuery.

  • Разметка

    До появления HTML5 форма поиска делалась обычным текстовым полем, с постепенным приходом в нашу жизнь новой версии языка разметки для нее появился специальный тип поля search . Так что в HTML коде современного сайта мы можем увидеть что-то вроде этого:

    Результат кода в FF, Opera, IE9:

    И немного по другому в браузерах на движке вебкит (Chrome, Safari):

    Поле поиска в вебкитах

    Как видите, при фокусе на поле добавляется подсветка, а при вводе текста появляется кнопка очистки, при нажатии на нее содержимое поля удаляется, что само по себе достаточно удобно.

    Без CSS оформления наша форма поиска пока выглядит достаточно просто, в этой статье мы попробуем сделать нечто вроде этого:

    например: верстка формы поиска

    Если не планируется поддержка старых браузеров, пустой несемантичный элемент

    можно заменить псевдоэлементом:before .

    Особенности оформления поисковой формы

    Поскольку я решил использовать достаточно много CSS3 свойств, в старых браузерах Internet Explorer эти чудеса работать не будут, и чтобы добиться кроссбраузерности, нужно подключать костыли, что-то делать картинками и т.д.

    Первым делом хотелось бы обратить внимание на некоторые особенности, а именно:

    • стилизация в браузерах на движке вебкит
    • стилизация placeholder

    Стили формы поиска в браузерах Chrome, Safari

    Добавим к полю с классом.search какой-нибудь стиль:

    Search { background: #d8e6ef; border: 1px solid #000; }

    Результат на скриншоте:

    Search в браузерах FF, Opera, Chrome и Safari

    Как обычно в браузерах наблюдается шатание и разброд, в Chrome как-то странно работает border (появляются поля, как будто задаем padding), Safari же полностью игнорирует правила. Но есть решение в данной ситуации, добавляем такое правило в CSS-код:

    Search { -webkit-appearance: none; }

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

    Search:focus { outline: none; /* убрали подсветку при фокусе */ -moz-box-shadow: inset 0 0 2px #000; -o-box-shadow: inset 0 0 2px #000; -webkit-box-shadow: inset 0 0 2px #000; box-shadow: inset 0 0 2px #000; /* добавили внутреннюю тень в качестве альтернативы для всех браузеров */ }

    Остается избавиться от кнопки очистки. На самом деле ее можно легко стилизовать, заменив простой крестик каким-нибудь фоном, позиционировать и т.д., однако в моем примере она будет не нужна:

    /* правило только к элементу с классом search */ .search::-webkit-search-cancel-button { display: none; /* убрали кнопку очистки */ } /* или ко всем полям с типом search в документе */ input::-webkit-search-cancel-button { display: none; }

    Оформление текстовой подсказки placeholder

    К сожалению с текстовой подсказкой все немного сложнее, чем кажется на первый взгляд. Во-первых, она не работает в IE9, не говоря уже о старых браузерах, поэтому в критичных местах, где обязательно изначально нужен какой-то текст в поле, следует использовать JavaScript. Во-вторых, placeholder плохо поддается оформлению в браузерах Firefox, Chrome, Safari и совсем не поддается в Opera:

    :-moz-placeholder { color: #304e62; /* изменили цвет в FF */ } ::-webkit-input-placeholder { color: #304e62; /* изменили цвет в вебкитах */ }

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

    Я рассмотрел особенные моменты, при которых могли возникнуть трудности, остальная часть для более-менее опытного верстальщика проблем вызвать не должна.

    Скрипты jQuery

    Напоследок добавим немного скриптов нашей форме, а именно:

    • сделаем отмену запроса и вывод сообщения об ошибке при отправлении пустого поля
    • при фокусе на поле добавим небольшую всплывающую подсказку внизу

    Очень просто это все реализовать мощью jQ, у меня получился такой код с комментариями:

    $(function() { /* обрабатываем отправку формы */ $(".search-form").submit(function() { var errVal = "пустой запрос"; /* Если поле пустое или содержит значение errVal */ if($(".search").val() == "" || $(".search").val() == errVal) { /* добавить в поле значение errVal, изменить цвет фона и */ $(".search").val(errVal).css({backgroundColor: "rgba(0,0,0,.1)"}); /* возвратить false - форма не отправляется */ return false; }; }); /* при фокусе на поле */ $(".search").focus(function() { /* выставить пустое значение поля, задать цвет фона в изначальный */ $(this).val("").css({backgroundColor: "#d8e6ef"}); /* показать всплывающую подсказку */ $(".notice").fadeIn(400); }); /* при снятии фокуса */ $(".search").blur(function() { /* убрать всплывающую подсказку */ $(".notice").fadeOut(400); }); });

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

    Итоги

    Таким образом мы сверстали и запрограммили поисковую форму для сайта, работает в последних версиях Firefox, Chrome, Opera, Safari и IE9+. При большом желании можно сделать более-менее кроссбраузерную версию, начиная хоть с IE6.

    Проверено

    • Internet Explorer 9+
    • Opera
    • Firefox
    • Chrome
    • Safari

    Помощь проекту

Похожие статьи

© 2024 teslya--show.ru. Windows. Интернет. Программы. Восстановление данных. Вирусы.