Создаем горизонтальное выпадающее меню на CSS
В предыдущей статье “Создаем вертикальное меню на CSS” был освещен вопрос построения вертикального меню с подменю.
В этой статье будет логическое продолжение этого вопроса и мы научимся делать горизонтальное меню с выпадающим подменю. Принцип построение и функционирования такой навигации очень похож на вертикальное меню, с той лишь разницей, что она будет располагаться горизонтально. В основе заложен тот же самый принцип — свойство со значениями и .
При построении горизонтального меню нужно быть внимательным с принципом специфичности CSS, то есть — с вложенностью и каскадностью правил. Хорошим подспорьем в этом вопросе является SASS (SCSS), благодаря которому исключаются ошибки при соблюдении каскадности и наследовании свойств.
Код, написанный на SASS (SCSS) короче и логически читается проще, чем CSS. Поэтому, рекомендую изучить этот вопрос в статьях “SASS (SCSS) в картинках — Часть 1”, “SASS (SCSS) в картинках — Часть 2”.
Мы же приступим к созданию горизонтального меню с подменю “на коленках”. Почему говорю так? Дело в том, что существует масса готовых примеров и кода, а также генераторов различных меню. Но они неинтересны — нам нужно разобраться в принципе построения и возможности самому написать такую навигацию. Как обычно, начинаем с каркаса меню, выполненного на HTML:
Структура подобного меню абсолютно одинакова со структурой вертикального меню. Также имеется внешний маркированный список с пунктами в виде ссылок, перед некоторыми из которых добавлены дополнительные подменю, выполненные также в виде маркированного списка.
Различие между внешним и внутренним меню в классах, с помощью которых они будут видоизменяться. Помимо этого вы можете заметить, что у некоторых ссылок есть класс , но о нем мы поговорим позже.
Приступим к оформлению нашего меню с помощью CSS. Сразу оговорюсь, что примеры кода, представленного здесь, написаны на SASS (SCSS). Начнем с того, что расположим навигацию горизонтально:
Думаю, ничего загадочного в этой части кода нет. Делаем отступ для меню и располагаем элементы внутри него горизонтально с помощью свойства . Предотвращаем схлопывание ( ) блока-родителя , прописав для него .
Чтобы пункты меню были легко различимы, сделаем промежуток между ними с помощью левого в 1px. И для аккуратности уберем левый у первого элемента .
Далее оформляем ссылки внутри пунктов . Делаем ссылки блочными, чтобы кликабельной была вся область пункта навигации и задаем для нее высоту. Также указываем интерлиньяж, чтобы выровнять текст по вертикали и для выравнивания по горизонтали. Цвет фона и цвет текста — как обычно.
Помимо этого, делаем ссылки с относительным позиционированием — оно нам пригодиться позже, когда будем отрисовывать треугольники. В этом коде стоит обратить внимание только на один момент — ширина элемента задается жестко. Это делается для того, чтобы основное меню не дергалось вправо-влево.
Возможна ситуация, когда пункт подменю по ширине будет больше, чем пункт основного меню, и тогда ребенок “растянет” своего родителя.
При скрытии же подменю пункты основного меню будут “сжиматься”, уменьшая ширину до своей собственной. Вот для этой цели и применяется явное задание ширины элемента :
Продолжим стилизацию нашей навигации и займемся подменю, а точнее — его подпунктами . Уберем у этих элементов плавание влево и левый , чтобы они не наследовали эти свойства. Убираем плавание, чтобы элементы расположились вертикально, а левый — убрать “лесенку”:
Стилизуем ссылки пунктов подменю. Делаем фоновую заливку чуть светлее, чтобы отличалась от основного меню, а текст — чуть темнее по той же причине. Ну и анимация пунктов при наведении курсора мыши:
Теперь самое главное — сделаем подпункты меню выпадающими. Для этого сначала спрячем его, убрав из DOM-модели HTML-документа с помощью значения свойства :
… а затем будем показывать его только при наведении курсора мыши на пункт меню. Код здесь может показаться немного непонятным, но знак амперсанда означает тоже, что и класс :
Все — наше меню создано и работает. Давайте немного приукрасив его, придав функциональности. А именно — на данный момент визуально невозможно различить, у какого пункта основного меню есть подменю, а у какого — нет. Для этого “продрисуем” к нужным пунктам небольшой треугольник с помощью псевдо-класса .
Как раз здесь нам и понадобиться относительное позиционирование для ссылок, о котором говорилось ранее. Создание стрелки “поручим” отдельному классу , который будем “вешать” только на нужные нам ссылки:
Вот, в принципе, и все. Основная задача выполнена и горизонтальное меню с выпадающим подменю у нас работает. Конечно, можно озадачиться целью “окрасить” активный пункт основного меню в тот же цвет, что и у подменю. Но эта проблема не входит в рассмотрение поставленной нами задачи. Ниже представлен полный код правил CSS (SCSS) для нашего меню:
How TO — Hoverable Dropdown
Learn how to create a hoverable dropdown menu with CSS.
Dropdown
A dropdown menu is a toggleable menu that allows the user to choose one value from a predefined list:
Create A Hoverable Dropdown
Create a dropdown menu that appears when the user moves the mouse over an element.
Step 1) Add HTML:
Example
Example Explained
Use any element to open the dropdown menu, e.g. a <button>, <a> or <p> element.
Use a container element (like <div>) to create the dropdown menu and add the dropdown links inside it.
Wrap a <div> element around the button and the <div> to position the dropdown menu correctly with CSS.
Step 2) Add CSS:
Example
/* Dropdown Button */
.dropbtn <
background-color: #04AA6D;
color: white;
padding: 16px;
font-size: 16px;
border: none;
>
/* The container <div> — needed to position the dropdown content */
.dropdown <
position: relative;
display: inline-block;
>
/* Dropdown Content (Hidden by Default) */
.dropdown-content <
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
>
/* Links inside the dropdown */
.dropdown-content a <
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
>
/* Change color of dropdown links on hover */
.dropdown-content a:hover
/* Show the dropdown menu on hover */
.dropdown:hover .dropdown-content
/* Change the background color of the dropdown button when the dropdown content is shown */
.dropdown:hover .dropbtn
Example Explained
We have styled the dropdown button with a background-color, padding, etc.
The .dropdown class uses position:relative , which is needed when we want the dropdown content to be placed right below the dropdown button (using position:absolute ).
The .dropdown-content class holds the actual dropdown menu. It is hidden by default, and will be displayed on hover (see below). Note the min-width is set to 160px. Feel free to change this. Tip: If you want the width of the dropdown content to be as wide as the dropdown button, set the width to 100% (and overflow:auto to enable scroll on small screens).
Instead of using a border, we have used the box-shadow property to make the dropdown menu look like a «card». We also use z-index to place the dropdown in front of other elements.
The :hover selector is used to show the dropdown menu when the user moves the mouse over the dropdown button.
How to make a pure css based dropdown menu?
I am looking horizontal dropdown menu pure css based and browser compatible.
i am looking like mentioned below example
![]()
7 Answers 7
see this is pure css bases dropdown menu:-
HTML
CSS
Tested in IE7 — 9 and Firefox: http://jsfiddle.net/WCaKg/. Markup:
View code online on: WebCrafts.org
You don’t have to always use ul elements to achieve that, you can use other elements too as seen below. Here there are 2 examples, one using div and one using select .
This examples demonstrates the basic functionality, but can be extended/enriched more. It is tested in linux only (iceweasel and chrome).
Create simple drop-down menu using HTML and CSS
There is different ways to make dropdown menu using css. Here is simple code.
CSS Dropdown Menu: How to Make It + HTML Tutorial

A dropdown menu contains a list of pages and subpages. Users can access its content by clicking on or hovering over the menu.
This design element reduces the clutter of buttons, links, and text which is useful for enhancing a website or an app’s user experience on small screens.
Keep reading as we will cover the steps to create a dropdown menu using HTML and CSS. You will also learn to apply styles to the newly built dropdown menu to match your project’s branding.
Creating a CSS Dropdown Menu
This tutorial requires a text editor to create the HTML and CSS file containing the dropdown menu’s code. Alternatively, you can do this through the File Manager of your hosting control panel. The following dropdown menu guide will use the latter method.
Step 1. Creating a File With HTML Code
To begin, create an HTML file for the actual dropdown menu content and syntax. Navigate to the File Manager from your hPanel dashboard and generate a new file called menu.html inside the public_html directory.
The menu.html file will contain the dropdown menu’s elements ‒ one parent element with five menu items. Each sub-menu will redirect users to different pages on your website.
Add the following code to the menu.html file:
The dropdown, mainmenubtn, and dropdown-child classes represent different HTML elements. CSS will use them to access a specific element and alter its design.
This is how the HTML menu will look without any CSS rules:

Pro Tip
Don’t forget to replace the links inside the href attributes with the URLs of your website pages and rename the sub-menus to reflect the actual page content.
Step 2. Adding CSS and Creating the Dropdown Effect
Now that you have HTML elements to work with, let’s create the dropdown effect and CSS rules for each of them.
Generate an internal stylesheet within the menu.html file by placing the following code inside the <style> element:
Pro Tip
In this example, the CSS styles are placed in the same HTML file (internal stylesheet). Use external CSS by linking the HTML document to a separate CSS file for easier modification.
The .mainmenubtn class name contains the CSS properties of the dropdown button. It sets the button’s background and font colors and omits the border. The cursor property dictates that the mouse cursor will change to the hand with the index finger extended symbol when hovering over the dropdown button.
Adding a hover selector to the .mainmenubtn class determines what the dropdown menu will look like when a user hovers over it.
The .dropdown class sets the dropdown menu’s position. In the above example, the CSS rules position the menu items under the parent menu. The inline-block property makes them appear without having a line break separating them.
The .dropdown-child class refers to the actual dropdown menu content. Using a display value of none makes the sub-menus invisible. .dropdown:hover .dropdown-child turns the entire element into a hoverable dropdown menu.
Pro Tip
Feel free to experiment with other CSS properties to get the desired design. You can even add JavaScript to create a responsive dropdown menu with dynamic animations.
Once you’re done, save and download the file. Here’s what the dropdown menu will look like when you open it on a web browser:

Examples of HTML and CSS Dropdown Menus
Plenty of modern CSS dropdown menu templates are available so you don’t have to code one from scratch. At the very least, they’re a great source of inspiration.
The following dropdown menu template by kkrueger utilizes HTML and CSS. Each parent menu smoothly expands on hover, creating a dynamic and memorable look for the web page.
Another example comes from Bhakti Pasaribu. He utilizes JavaScript to create an interactive dropdown menu. The options appear with a flip animation upon clicking the parent menu. Another animation replaces the parent menu with the selected option, creating a seamless transition effect. This dropdown menu template is simple and dynamic in a unique way.
Minimalism enthusiasts may like what Chris Ota has to offer. His collapsable menu is subtle and doesn’t hog too much space. Still, it places user experience at the forefront. You can easily replace the list item descriptions with icons, further strengthening your site’s branding.
If you’re looking for a more flashy menu with visual effects, we recommend checking out the Molten dropdown menu by Zealand. It utilizes CSS keyframe animations to create an eye-catching flickering flame around the navigation bar.
Recursive Hover Nav by sean_codes offers a mega menu solution without obstructing the site’s user experience. The multi-level dropdown menu is built using HTML, CSS, and JavaScript.
As your mouse hovers over the parent menu, the sub-menus appear with a slide transition animation. While it doesn’t have flashy effects like the other examples, this template is more practical when it comes to managing a menu with lots of content.
Pro Tip
When designing a dropdown menu, make sure to consider the site’s user experience. A beautifully made CSS dropdown menu doesn’t guarantee great usability. In most cases, less is more.
Conclusion
Having a dropdown menu makes it easier to design an effective user interface. It reduces the number of elements cluttering your web page and, with an appropriate design, enhances the site’s aesthetics.
You can create a dropdown menu from scratch using HTML, CSS, and JavaScript. Alternatively, adopt one of the many dropdown menu templates coded by professional designers and adjust it to your preference.
We hope this article has provided you with a better understanding of how to design a CSS dropdown menu. Good luck.
Linas started as a customer success agent and is now a full-stack web developer and Technical Team Lead at Hostinger. He is passionate about presenting people with top-notch technical solutions, but as much as he enjoys coding, he secretly dreams of becoming a rock star.