Как сделать поисковую строку в html css
Перейти к содержимому

Как сделать поисковую строку в html css

  • автор:

Как создать поле поиска

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

В этой статье мы пошагово покажем, как можно создать поле поиска с помощью CSS и HTML.

  1. Создайте HTML
  • Создайте тег <form>, который используется для добавления HTML форм к веб-странице для пользовательского ввода.
  • Добавьте тег <input> внутри элемента <form>.
  • Добавьте также placeholder с выражением «Search here!» и класс «Search».
  • Добавьте другой input c классом «submit» и значение «search». ска, используя только CSS и HTML.

Теперь у нас есть поле поиска, но необходимо добавить стиль.

  1. Добавьте CSS

Есть три элемента, к которым необходимо применить стиль: «form», «search» и»submit».

  • Добавьте фоновый цвет текстовой части (body).
  • Начните оформление классов «form», «search»и «submit».
  • Установите width, margin, padding, и font-size.

После того, как все свойства добавлены, запустите код и увидите результат!

Как сделать поиск по сайту на HTML

Как сделать поиск по сайту на HTML

На этом уроке мы научимся встраивать строку поиска в адаптивное меню навигации, используя при этом только HTML/CSS код.

Демонстрация примера.

HTML разметка

Внутри меню навигации <nav> у нас будет три пункта меню в виде ссылок и встроен блок с классом search-box, внутри которого форма для поиска с полем поиска и кнопкой.

Вся эта конструкция до стилизации выглядит таким вот образом.

Как сделать поиск по сайту на HTML.

CSS код

Зададим светло-зелёный цвет фона для панели навигации.

nav <
background-color: #dcedc8;
>

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

nav a <
float: left;
display: block;
>

Меняем цвет фона под ссылками при наведении.

nav a:hover <
background-color: #8bc34a;
>

Стилизуем активный элемент для выделения пункта меню текущей страницы.

nav a.active <
background-color: #8bc34a;
color: #fff;
>

Располагаем контейнер для поиска на правой части панели навигации.

nav .search-box <
float: right;
>

Стилизуем поле для поиска внутри панели навигации.

nav input[type=text] <
padding: 5px;
margin-top: 7px;
border: none;
>

Стилизуем кнопку Отправить внутри контейнера с поиском, располагая её правее по отношению к строке поиска (float:right).

nav .search-box button <
float: right;
padding: 5px;
margin-top: 7px;
margin-right: 15px;
background: #8bc34a;
border: none;
cursor: pointer;
>

Меняем цвет кнопки при наведении.

nav .search-box button:hover <
background: #bdbdbd;
>

До ширины экрана 625 пикселей панель навигации выглядит хорошо.

Как сделать поиск по сайту на HTML.

После 625 пикселей конструкция ломается, необходимо делать медиа-запрос для маленьких устройств.

Как сделать поиск по сайту на HTML.

Медиа-запросы

Первым делом отменим обтекание везде, где оно было (float:none), это позволит всем элементам занять вертикальное положение, на ширине экрана меньше, чем 625 пикселей.

@media screen and (max-width: 625px) <
nav .search-box <
float: none;
>
nav a, nav input[type=text], nav .search-box button <
float: none;
display: block;
text-align: left; /* ссылки слева */
width: 100%; /* на всю ширину экрана */
>
nav input[type=text] <
border: 1px solid #689f38; /* рамка для строки поиска */
>
>

Как сделать поиск по сайту на HTML.

Добавить иконку на кнопку Отправить

1) Добавить ссылку между тегами head:

<link rel=»stylesheet» href=»https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css»>

2) Вставить иконку между тегами button:

Как сделать поиск по сайту на HTML.

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

Посмотреть код целиком можно на Codepen

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Порекомендуйте эту статью друзьям:

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

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

Комментарии ( 2 ):

Спасибо тебе, добрый человек! Ради отзыва решил даже зарегистрироваться на сайте. Это единственный поиск, который корректно подошел к моему сайту. За что огромное спасибо!

++++ очень качественно, спасибо.

Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

How to Add a Search Bar in HTML

In this tutorial, we are going to add a search bar in HTML to your site!

I will walk you through all the components you need to add a search bar in HTML and connect it to Google to search.

Google will open in a new tab and only show results for your site.

For those in a rush, the complete solution is at the bottom of the page. For those who want the deep dive keep reading!

Let’s start with the HTML that we need to create a form.

HTML Form

The first thing we need to add is the bar itself. This uses a few HTML elements:

  • <form> — This element is for user input
  • <input> — This element has many types the one we will use today is search
  • <button> — This element will submit the form and start the search

Here is what the HTML will look like:

The above HTML is all we need to create a search bar. There are a few attributes that we are using on the <input> tag. Let’s look at these in more detail:

  • type — This sets how the input looks on the screen. There are many types such as password, checkbox and radio yet here we are using search
  • id — Setting an ID can make it easy to reference the input box from JavaScript which we will use later
  • name — It is common to use “q” for the search query box name
  • placeholder — This is some text that gives a hint to the user on what the input is for

When the HTML displays on the browser it looks like this:

For the input, we have used the type search but there is also a text type. It can be a bit confusing on which one you should pick. The two input types are almost the same except the search type has some extra functionality. For example, some browsers will add a delete button to the input tag for you:

For search boxes, it makes sense to use the search input type and that is what we are going to use here.

Our form is not quite finished yet, we need to make sure that screen readers can use it for accessibility.

To do this we have to make two changes to the form:

  1. We need to add a role to the form with the value of “search”. Setting this will cause the screen readers to announce that this form is a search form.
  2. We add a aria-label attribute to the <input> element. The screen reader will read aloud the value of this attribute. Set a value that describes what text the search form returns such as “Search through our site content”.

This is our final HTML:

Next, we are going to look at making a form pretty by styling the form with CSS.

CSS adds style to the search bar changing its look and feel.

One addition that can help the user find the search box is to add a magnifying glass or search icon. We will add one of these to the button and create a search box that looks like this:

It’s amazing what a bit of color and an icon can do! Looks much better right?

Let’s look at what we have changed to make it look like this.

First, we have added some color to the form itself:

We have set the width and height of the form. We also arrange the items in the form using the flex display.

Next, we change the look of the input search box:

The first line above resets the search box all: unset; design. Many browsers add their own design and it can be hard to style. This can make it easier to style as we need.

Then we set the font and make sure that the search bar fills the space with height and width. Lastly, we have added a bit of padding.

The next CSS rule is a bit strange! It allows us to set the style of the placeholder text inside the search box. The default is grey text, to change this we need to use this rule:

The last CSS rules change the look and feel of the button. You can see here that we have replaced the search button with a search icon.

To do this I have changed the HTML of the button to now include a svg . The svg is an image of the search icon, it now looks like this:

We can then style these two html elements like this:

We have used the all: unset; rule again to reset the button to its default. Then set a height and width of 44px this is a good size for fingers on touch screens.

Then we set the height and width of the icon and set the color to white ("#fff”).

Now our search bar is almost ready! Except nothing happens when we press the search button.

The last step for us is to hook up the button to JavaScript.

JavaScript

We are going to do a Google search when someone searches in our search bar.

To do this we need to write some code that will:

  • Add an event listener to the form so we know when someone presses the search button
  • Get the text value from the query box
  • Build a Google URL that searches a specific site
  • Opens a new tab with Google and the search query

Google allows you to search a specific site if you add site: to the query. For example, if you wanted to search PageDart for the term lazy loading you could add this in Google:

site:pagedart.com lazy loading

The great thing about this search query is that it only returns results for the site you specify. You filter Google results and no other site will appear in the results. We can use this trick to create a search results page from our search bar.

Here is the code that can do this:

The first thing we do is attach some variables to the form and search input box. Then we set the Google URL and set the site variable:

If you want to search your site then change const site = ‘pagedart.com’; to your website const site = ‘example.com’; .

We then create a function that will run each time someone presses the search button. The function will then open Google in a new tab in the browser:

The last line in the code:

Add a listener to the form. It will listen for the submit button press and run the function each time.

Now when you enter a search query and press the search icon a new tab will open up with your site and the search query.

Complete Solution

Now we have covered all the parts of a search bar:

  • HTML of the form
  • CSS to add color and design
  • JavaScript to process the form input

You can see a working codepen example.

Here is the complete HTML:

How to Add a Search Bar in HTML, Final Thoughts

You have learned in this tutorial how to add a search bar in HTML. We have covered:

  • How to create a small HTML form
  • How to design the form using CSS
  • How to write JavaScript to interact with the form

You have also learned how you can use JavaScript to connect the form to Google. Performing a search only on your site.

Using the special site search on Google you can get Google results only for your site.

31 Search Form HTML For Web Design

Search component is an important component in the website. It makes it easy for users to find the content they want in your website. In today’s post, we’ll take a look at some beautiful Simple search box HTML.

Stylish search box in HTML

You can see the result below.

CSS Search Box With Icon

You can see the result below.

Stylish Search Box In HTML CSS Code

You can see the result below.

Search Box HTML CSS

You can see the result below.

Search Box HTML Code Design

You can see the result below.

Simple Search Box HTML

You can see the result below.

CSS Search Bar Styling

You can see the result below.

Responsive Search Bar

You can see the result below.

Responsive search bar CSS

You can see the result below.

Simple search box CSS

You can see the result below.

Search Form Style CSS

You can see the result below.

CSS Search Box Examples

You can see the result below.

Animated Search Bar

You can see the result below.

Search Box By Scene.js

You can see the result below.

Rounded Search Bar HTML

You can see the result below.

Search Input CSS

You can see the result below.

Input Type Search CSS

You can see the result below.

Input With Search Icon CSS

You can see the result below.

Search Icon In Input Field

You can see the result below.

Custom Search Bar HTML

You can see the result below.

Search Bar For Website HTML

You can see the result below.

Search Bar Design

You can see the result below.

Transparent search bar CSS

You can see the result below.

Bootstrap Search Box With Icon

You can see the result below.

Website Search Bar Design

You can see the result below.

Search Box With Icon Inside

You can see the result below.

Bootstrap Search Box With Icon Inside

You can see the result below.

Javascript Search Box

You can see the result below.

Animation Search Bar By GSAP

You can see the result below.

Search Bar HTML Template

You can see the result below.

Search bar template HTML CSS

You can see the result below.

Summary

I hope the article will provide you with useful Responsive search bar for web development and if you have any questions, just send an email and I will respond as soon as possible. I hope you continue to support the site so that I can write more good articles. Have a nice day!

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

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