- How to create a vertical tab menu with CSS and JavaScript?
- Steps to Create Tabs
- Example.html
- TAB First
- TAB Second
- Tab Third
- Example.css
- Example.js
- Complete Example
- TAB First
- TAB Second
- Tab Third
- How TO — Vertical Tabs
- Vertical Tabs
- Create Togglable Vertical Tabs
- Example
- London
- Paris
- Tokyo
- Example
- Example
- Вертикальные адаптивные табы-вкладки
- HTML код адаптивных вкладок
- Код стилей адаптивных вкладок
- Как сделать — Вертикальные вкладки
- Вертикальная вкладки
- Создание переключаемых вертикальных вкладок
- Пример
- Лондон
- Париж
- Токио
- Пример
- Пример
How to create a vertical tab menu with CSS and JavaScript?
In this article, we will discuss how to create a vertical tab menu with CSS and JavaScript.
Tabs are containers whose main purpose is to show and navigate through the diverse content of the website. Tabs are commonly used to manage the space and make the website more user−friendly without reloading too many times. The content in these tabs are usually closely related but mutually exclusive.
There are several types of tabs which can be created and used in various cases −
- Horizontal tabs
- Horizontal with Secondary Tabs
- Frameless Horizontal Tabs
- Vertical Tabs
- Vertical Tabs with Second Tabs
Vertical tabs also divide the data but are arranged vertically instead. They share all the major characteristics of the horizontal tabs but have better scalability if the number of tabs is higher. Vertical tabs also provide an additional description compartment to summarize the tab’s content.
Steps to Create Tabs
Following are the steps to be followed to create tabs with CSS and JavaScript −
- In the body, the tag creates the tab under the div tag which custom data attributes.
- Create another div tag to store the content of the tab with the specified id.
- Specified data attributes for each content tag to display only one tab of content at a time
- Using JavaScript, we can display the content of the tab.
Example.html
In this part, we are building the page’s body structure by constructing three buttons (Tab1, Tab2, and Tab3) in vertical direction and three div paragraphs. As you can see from the code below.
TAB First
Tutorialspoint Easy To learn
TAB Second
Hyderabad Telangana, Madhapur Above D-Mart 4th Floor.
Tab Third
Lorem ipsum dolor sit amet consectetur adipisicing elit. Modi magniomnis reiciendis ullam perspiciatis labore obcaecati tenetur vitae eteius voluptate optio saepe porro, officiis quos praesentium enim undesequi?
Example.css
In this part, Style is added to the page. Styling the width and height of the button, as well as creating a hover effect and altering the background color of the button when you hover over it.
/*CSS*/ * < box-sizing: border-box; >.tab < float: left; border: 1px solid #ccc; background-color: #f1f1f1; width: 20%; >/* Style the buttons that are used to open the tab content */ .tab button < display: block; background-color: inherit; color: black; padding: 22px 16px; width: 100%; border: none; outline: none; cursor: pointer; transition: 0.3s; >.tab button:hover < background-color: rgb(18, 84, 198); >.tabcontent
Example.js
In this part, we are constructing a function selectTab and passing tabindex as an argument, as well as adding the style display attribute, so that when you click on the button, the tab content appears on the page. As you can see from the code below.
Complete Example
/*CSS*/ * < box-sizing: border-box; >.tab < float: left; border: 1px solid #ccc; background-color: #f1f1f1; width: 20%; >/* Style the buttons that are used to open the tab content */ .tab button < display: block; background-color: inherit; color: black; padding: 22px 16px; width: 100%; border: none; outline: none; cursor: pointer; transition: 0.3s; >.tab button:hover < background-color: rgb(18, 84, 198); >.tabcontentTAB First
Tutorialspoint Easy To learn
TAB Second
Hyderabad Telangana, Madhapur Above D-Mart 4th Floor.
Tab Third
Lorem ipsum dolor sit amet consectetur adipisicing elit. Modi magniomnis reiciendis ullam perspiciatis labore obcaecati tenetur vitae eteius voluptate optio saepe porro, officiis quos praesentium enim undesequi?
How TO — Vertical Tabs
Learn how to create a vertical tab menu with CSS and JavaScript.
Vertical Tabs
Tabs are perfect for single page web applications, or for web pages capable of displaying different subjects.
Create Togglable Vertical Tabs
Step 1) Add HTML:
Example
London
London is the capital city of England.
Paris
Paris is the capital of France.
Tokyo
Tokyo is the capital of Japan.
Create buttons to open the specific tab content. All elements with class=»tabcontent» are hidden by default (with CSS & JS) — when the user clicks on a button — it will open the tab content that «matches» this button.
Step 2) Add CSS:
Style the buttons and the tab content:
Example
/* Style the tab */
.tab float: left;
border: 1px solid #ccc;
background-color: #f1f1f1;
width: 30%;
height: 300px;
>
/* Style the buttons that are used to open the tab content */
.tab button display: block;
background-color: inherit;
color: black;
padding: 22px 16px;
width: 100%;
border: none;
outline: none;
text-align: left;
cursor: pointer;
transition: 0.3s;
>
/* Change background color of buttons on hover */
.tab button:hover background-color: #ddd;
>
/* Create an active/current «tab button» class */
.tab button.active background-color: #ccc;
>
/* Style the tab content */
.tabcontent float: left;
padding: 0px 12px;
border: 1px solid #ccc;
width: 70%;
border-left: none;
height: 300px;
>
Step 3) Add JavaScript:
Example
function openCity(evt, cityName) <
// Declare all variables
var i, tabcontent, tablinks;
// Get all elements with and hide them
tabcontent = document.getElementsByClassName(«tabcontent»);
for (i = 0; i < tabcontent.length; i++) tabcontent[i].style.display = "none";
>
// Get all elements with and remove the class «active»
tablinks = document.getElementsByClassName(«tablinks»);
for (i = 0; i < tablinks.length; i++) tablinks[i].className = tablinks[i].className.replace(" active", "");
>
// Show the current tab, and add an «active» class to the link that opened the tab
document.getElementById(cityName).style.display = «block»;
evt.currentTarget.className += » active»;
>
Tip: Also check out How To — Horizontal Tabs.
Вертикальные адаптивные табы-вкладки
Хочу сразу сказать что, преимущество данной реализации вкладок-табов. Это не сомненно их адаптивный дизайн , где Ваш контент в каждой вкладке располагается справа за ее названием ( аналог аккордеона).
Кроме того, каждая таб-вкладка в данной реализации имеет одинаковый (HTML-код), что сильно упрощает его интеграцию буквально в любую CMS (без надобности выставлять разные ID, класс и другие атрибуты).
Простая реализация вертикальных адаптивных табов-вкладок для сайта, на на jQuery и CSS. Не сложная установка за пару минут. Вам понадобится лишь скопировать код на сайт и подключить стили и скрипт выполнения.
HTML код адаптивных вкладок
Этот код Вам необходимо вставить в то место где должно быть отображение вкладок.
1 Пункт Ваше название вкладки Ваше описание вкладки
10 Пункт Ваше название вкладки Ваше описание вкладки
Код стилей адаптивных вкладок
Данный код нужно скопировать в общий файл стилей, ну или создать отдельный файл и подключить его.
.tabs * .tabs .tabs:after .tabs .tab .tab-toggle .tabs .tab .tab-toggle .tab-nums < padding: 0 10px 0 0; display: flex; align-items: center; justify-content: center; border-radius: 16px 0 0 16px; >.tabs .tab .tab-toggle .tab-nums .tab-num < color: #337AB7; font-size: 18px; font-weight: bold; border-radius: 50%; background: #FFF; border: 3px solid #337AB7; width: 34px; height: 34px; display: flex; align-items: center; justify-content: center; margin-left: -20px; position: relative; z-index: 1; >.tabs .tab .tab-toggle .tab-nums .tab-tab < padding: 0 12px 0 24px; margin-left: -20px; font-size: 13px; font-weight: bold; border: 2px solid #BFE2FF; background: #BFE2FF; color: #337AB7; border-radius: 0 22px 22px 0; height: 34px; display: flex; align-items: center; justify-content: center; >.tabs .tab .tab-toggle .tab-name < padding: 6px 0; text-align: left; text-transform: uppercase; font-size: 16px; font-weight: bold; >.tabs .tab .tab-toggle:after < content: ""; background-image: url("dаta:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 320 512'%3e%3cpath fill='%23000000' d='M143 352.3L7 216.3c-9.4-9.4-9.4-24.6 0-33.9l22.6-22.6c9.4-9.4 24.6-9.4 33.9 0l96.4 96.4 96.4-96.4c9.4-9.4 24.6-9.4 33.9 0l22.6 22.6c9.4 9.4 9.4 24.6 0 33.9l-136 136c-9.2 9.4-24.4 9.4-33.8 0z'/%3e%3c/svg%3e"); background-repeat: no-repeat; background-size: contain; background-position: center; position: absolute; width: 20px; height: 20px; display: block; right: 10px; top: 50%; transform: rotate(0deg) translateY(-50%); > .tabs .tab .tab-toggle.active .tabs .tab .tab-toggle.active .tab-nums .tab-num .tabs .tab .tab-toggle.active .tab-nums .tab-tab .tabs .tab .tab-toggle.active .tab-name .tabs .tab .tab-toggle.active:after < background-image: url("dаta:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 320 512'%3e%3cpath fill='%23337AB7' d='M143 352.3L7 216.3c-9.4-9.4-9.4-24.6 0-33.9l22.6-22.6c9.4-9.4 24.6-9.4 33.9 0l96.4 96.4 96.4-96.4c9.4-9.4 24.6-9.4 33.9 0l22.6 22.6c9.4 9.4 9.4 24.6 0 33.9l-136 136c-9.2 9.4-24.4 9.4-33.8 0z'/%3e%3c/svg%3e"); > .tabs .tab .tab-toggle.active:after .tabs .content < overflow: hidden; padding: 0; transition: opacity 0.4s; visibility: hidden; opacity: 0; padding: 0 0 10px 0; max-height: 0; >.tabs .content.active < max-height: 5000px; visibility: visible; opacity: 1; >@media screen and (min-width: 992px) < .tabs < position: relative; transition: all 0.5s; >.tabs .tab < float: left; clear: left; width: 30%; >.tabs .tab .tab-toggle < text-align: left; >.tabs .tab .tab-toggle:after < transform: rotate(-90deg) translateX(50%); >.tabs .tab .tab-toggle.active:after < transform: rotate(-90deg) translateX(50%) translateY(0); >.tabs .content < position: absolute; right: 0; top: 0; width: 70%; opacity: 0; padding: 0 0 30px 40px; transition: opacity 0.4s; >.tabs .content.active < opacity: 1; padding: 0 0 10px 40px; >>
Теперь осталось подключить скрипт выполнения данной работы. (Подключение скрипта выполняется добавлением в начале и в конце кода вот так
let wrapper = $(".tabs"); let tabToggle = wrapper.find(".tab-toggle"); function openTab() < let content = $(this).parent().next(".content"), activeItems = wrapper.find(".active"); if ($(window).width() >991) < if(!$(this).hasClass('active')) < $(this).add(content).add(activeItems).toggleClass('active'); wrapper.css('min-height', content.outerHeight()); >> else < $(this).add(content).toggleClass('active'); >>; tabToggle.on('click', openTab); tabToggle.first().trigger('click');
Если хотите можете скачать уже готовые варианты, просто скопируете на хостинг и подключите файлы и стили.
Как сделать — Вертикальные вкладки
Узнать, как создать вертикальное меню вкладок с помощью CSS и JavaScript.
Вертикальная вкладки
Вкладки идеально подходят для одностраничных веб-приложений или для веб-страниц, способных отображения различных предметов.
Создание переключаемых вертикальных вкладок
Шаг 1) Добавить HTML:
Пример
Лондон
Лондон является столицей Англии.
Париж
Париж является столицей Франции.
Токио
Токио является столицей Японии.
Создайте кнопки для открытия определенного содержимого вкладки. Все элементы с class=»tabcontent» по умолчанию скрыты (с CSS & JS) — когда пользователь нажимает на кнопку — он откроет содержимое вкладки, которое «matches» эта кнопка.
Шаг 2) Добавить CSS:
Стиль кнопок и содержимого вкладок:
Пример
/* Стиль табуляции */
.tab float: left;
border: 1px solid #ccc;
background-color: #f1f1f1;
width: 30%;
height: 300px;
>
/* Стиль кнопок, которые используются для открытия содержимого вкладки */
.tab button display: block;
background-color: inherit;
color: black;
padding: 22px 16px;
width: 100%;
border: none;
outline: none;
text-align: left;
cursor: pointer;
transition: 0.3s;
>
/* Изменение цвета фона кнопок при наведении курсора */
.tab button:hover background-color: #ddd;
>
/* Создать активный текущий класс «вкладку кнопок» */
.tab button.active background-color: #ccc;
>
/* Стиль содержимого вкладки */
.tabcontent float: left;
padding: 0px 12px;
border: 1px solid #ccc;
width: 70%;
border-left: none;
height: 300px;
>
Шаг 3) Добавить JavaScript:
Пример
function openCity(evt, cityName) <
// Объявить все переменные
var i, tabcontent, tablinks;
// Получить все элементы с помощью and hide them
tabcontent = document.getElementsByClassName(«tabcontent»);
for (i = 0; i < tabcontent.length; i++) tabcontent[i].style.display = "none";
>
// Получить все элементы с помощью и удалить класс «active»
tablinks = document.getElementsByClassName(«tablinks»);
for (i = 0; i < tablinks.length; i++) tablinks[i].className = tablinks[i].className.replace(" active", "");
>
// Показать текущую вкладку и добавить класс «active» по ссылке, открывшей вкладку
document.getElementById(cityName).style.display = «block»;
evt.currentTarget.className += » active»;
>
Совет: Кроме того, проверить Как сделать горизонтальные вкладки.