Navbar
Содержание:
Dropdown Menu
Create a dropdown menu that allows the user to choose an option from a list:
Dropdown Menu
Link 1
Link 2
Link 3
This example is similar to the previous one, except that we add links inside the dropdown box and style them to fit a styled dropdown button:
Example
<style>/* Style The Dropdown Button */.dropbtn {
background-color: #4CAF50; color: white;
padding: 16px; font-size: 16px;
border: none; cursor: pointer;}/* 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: #f9f9f9;
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 {background-color: #f1f1f1}/* Show the
dropdown menu on hover */.dropdown:hover .dropdown-content {
display: block;}/* Change the background color of the dropdown
button when the dropdown content is shown */.dropdown:hover .dropbtn { background-color: #3e8e41;}</style><div class=»dropdown»> <button class=»dropbtn»>Dropdown</button>
<div class=»dropdown-content»> <a href=»#»>Link
1</a>
<a href=»#»>Link 2</a> <a href=»#»>Link 3</a> </div></div>
Dropdown Events
The following table lists all available dropdown events.
Event | Description | Try it |
---|---|---|
show.bs.dropdown | Occurs when the dropdown is about to be shown. | Try it |
shown.bs.dropdown | Occurs when the dropdown is fully shown (after CSS transitions have completed) | Try it |
hide.bs.dropdown | Occurs when the dropdown is about to be hidden | Try it |
hidden.bs.dropdown | Occurs when the dropdown is fully hidden (after CSS transitions have completed) | Try it |
Tip: Use jQuery’s event.relatedTarget
to get the element which triggered the dropdown:
Example
$(«.dropdown»).on(«show.bs.dropdown», function(event){ var x = $(event.relatedTarget).text(); // Get the text of the element
alert(x);});
More Examples
Example
/* CSS: */<style>.caret.caret-up { border-top-width: 0; border-bottom: 4px solid #fff;
}</style>/* JS: */<script>$(document).ready(function(){ $(«.dropdown»).on(«hide.bs.dropdown», function(){ $(«.btn»).html(‘Dropdown <span class=»caret»></span>’); }); $(«.dropdown»).on(«show.bs.dropdown», function(){ $(«.btn»).html(‘Dropdown <span class=»caret caret-up»></span>’); });});</script>
Example
<nav class=»navbar navbar-inverse»> <div class=»container-fluid»> <div class=»navbar-header»> <a class=»navbar-brand» href=»#»>WebSiteName</a> </div> <div> <ul class=»nav navbar-nav»> <li class=»active»><a href=»#»>Home</a></li> <li class=»dropdown»> <a class=»dropdown-toggle» data-toggle=»dropdown» href=»#»>Page 1 <span class=»caret»></span></a> <ul class=»dropdown-menu»> <li><a href=»#»>Page 1-1</a></li> <li><a href=»#»>Page 1-2</a></li> <li><a href=»#»>Page 1-3</a></li> </ul> </li> <li><a href=»#»>Page 2</a></li> <li><a href=»#»>Page 3</a></li> </ul> </div> </div></nav>
The following example adds a dropdown menu with a login form in the navbar:
Example
<ul class=»nav navbar-nav navbar-right»> <li class=»dropdown»> <a class=»dropdown-toggle» data-toggle=»dropdown» href=»#»>Login <span class=»glyphicon glyphicon-log-in»></span></a> <div class=»dropdown-menu»> <form id=»formlogin» class=»form container-fluid»> <div class=»form-group»> <label for=»usr»>Name:</label> <input type=»text» class=»form-control» id=»usr»> </div> <div class=»form-group»> <label for=»pwd»>Password:</label> <input type=»password» class=»form-control» id=»pwd»> </div> <button type=»button» id=»btnLogin» class=»btn btn-block»>Login</button> </form> <div class=»container-fluid»> <a class=»small» href=»#»>Forgot password?</a> </div> </div> </li></ul>
Example
<script>
$(document).ready(function(){ $(‘.dropdown-submenu a.test’).on(«click», function(e){ $(this).next(‘ul’).toggle(); e.stopPropagation(); e.preventDefault(); });
});</script>
In this example, we have created a custom class for multi-level dropdowns:
Example
/* CSS: */<style>.dropdown-submenu { position: relative;}.dropdown-submenu .dropdown-menu {
top: 0; left: 100%; margin-top: -1px;}</style>/* JS: */<script>
$(document).ready(function(){ $(‘.dropdown-submenu a.test’).on(«click», function(e){ $(this).next(‘ul’).toggle(); e.stopPropagation(); e.preventDefault(); });
});</script>
Menus
Icon BarMenu IconAccordionTabsVertical TabsTab HeadersFull Page TabsHover TabsTop NavigationResponsive TopnavNavbar with IconsSearch MenuSearch BarFixed SidebarSide NavigationResponsive SidebarFullscreen NavigationOff-Canvas MenuHover Sidenav ButtonsSidebar with IconsHorizontal Scroll MenuVertical MenuBottom NavigationResponsive Bottom NavBottom Border Nav LinksRight Aligned Menu LinksCentered Menu LinkEqual Width Menu LinksFixed MenuSlide Down Bar on ScrollHide Navbar on ScrollShrink Navbar on ScrollSticky NavbarNavbar on ImageHover DropdownsClick DropdownsDropdown in TopnavDropdown in SidenavResp Navbar DropdownSubnavigation MenuDropupMega MenuMobile MenuCurtain MenuCollapsed SidebarCollapsed SidepanelPaginationBreadcrumbsButton GroupVertical Button GroupSticky Social BarPill NavigationResponsive Header
Accessibility
The WAI ARIA standard defines an actual , but this is specific to application-like menus which trigger actions or functions. ARIA menus can only contain menu items, checkbox menu items, radio button menu items, radio button groups, and sub-menus.
Bootstrap’s dropdowns, on the other hand, are designed to be generic and applicable to a variety of situations and markup structures. For instance, it is possible to create dropdowns that contain additional inputs and form controls, such as search fields or login forms. For this reason, Bootstrap does not expect (nor automatically add) any of the and attributes required for true ARIA menus. Authors will have to include these more specific attributes themselves.
However, Bootstrap does add built-in support for most standard keyboard menu interactions, such as the ability to move through individual elements using the cursor keys and close the menu with the ESC key.
Create A Hoverable Dropdown
Create a dropdown menu that appears when the user moves the mouse over an
element.
Step 1) Add HTML:
Example
<div class=»dropdown»> <button class=»dropbtn»>Dropdown</button>
<div class=»dropdown-content»> <a href=»#»>Link
1</a>
<a href=»#»>Link 2</a> <a href=»#»>Link 3</a> </div></div>
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: #4CAF50; 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 {background-color: #ddd;}/* Show the
dropdown menu on hover */.dropdown:hover .dropdown-content {display: block;}/* Change the background color of the dropdown
button when the dropdown content is shown */.dropdown:hover .dropbtn {background-color: #3e8e41;}
Example Explained
We have styled the dropdown button with a background-color, padding, etc.
The class uses , which is needed when we want the
dropdown content to be placed right below the dropdown button (using ).
The class holds the actual dropdown menu. It is hidden by
default, and will be displayed on hover (see below). Note the 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 to 100% (and to
enable scroll on small screens).
Instead of using a border, we have used the 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 selector is used to show the dropdown menu when the user moves the
mouse over the dropdown button.
Images
SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison Slider
Usage
Via data attributes or JavaScript, the dropdown plugin toggles hidden content (dropdown menus) by toggling the class on the parent list item. The attribute is relied on for closing dropdown menus at an application level, so it’s a good idea to always use it.
On touch-enabled devices, opening a dropdown adds empty () handlers to the immediate children of the element. This admittedly ugly hack is necessary to work around a quirk in iOS’ event delegation, which would otherwise prevent a tap anywhere outside of the dropdown from triggering the code that closes the dropdown. Once the dropdown is closed, these additional empty handlers are removed.
Via JavaScript
Call the dropdowns via JavaScript:
still required
Regardless of whether you call your dropdown via JavaScript or instead use the data-api, is always required to be present on the dropdown’s trigger element.
Options
Options can be passed via data attributes or JavaScript. For data attributes, append the option name to , as in .
Name | Type | Default | Description |
---|---|---|---|
offset | number | string | function |
Offset of the dropdown relative to its target. When a function is used to determine the offset, it is called with an object containing the offset data as its first argument. The function must return an object with the same structure. The triggering element DOM node is passed as the second argument. For more information refer to Popper.js’s . |
|
flip | boolean | true | Allow Dropdown to flip in case of an overlapping on the reference element. For more information refer to Popper.js’s . |
boundary | string | element | ‘scrollParent’ | Overflow constraint boundary of the dropdown menu. Accepts the values of , , , or an HTMLElement reference (JavaScript only). For more information refer to Popper.js’s . |
reference | string | element | ‘toggle’ | Reference element of the dropdown menu. Accepts the values of , , or an HTMLElement reference. For more information refer to Popper.js’s . |
display | string | ‘dynamic’ | By default, we use Popper.js for dynamic positioning. Disable this with . |
popperConfig | null | object | null | To change Bootstrap’s default Popper.js config, see |
Note when is set to any value other than , the style is applied to the container.
Methods
Method | Description |
---|---|
Toggles the dropdown menu of a given navbar or tabbed navigation. | |
Shows the dropdown menu of a given navbar or tabbed navigation. | |
Hides the dropdown menu of a given navbar or tabbed navigation. | |
Updates the position of an element’s dropdown. | |
Destroys an element’s dropdown. |
Events
All dropdown events are fired at the ’s parent element and have a property, whose value is the toggling anchor element.
and events have a property (only when the original event type is ) that contains an Event Object for the click event.
Event | Description |
---|---|
This event fires immediately when the show instance method is called. | |
This event is fired when the dropdown has been made visible to the user (will wait for CSS transitions, to complete). | |
This event is fired immediately when the hide instance method has been called. | |
This event is fired when the dropdown has finished being hidden from the user (will wait for CSS transitions, to complete). |
Элементы меню
Компонент «NavBar» состоит из нескольких подкомпонентов, которые можно добавлять или исключать по мере необходимости.
Название или логотип компании
<nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <!-- Текстовая ссылка --> <a class="navbar-brand" href="#">Brand</a> .......... </nav>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <!-- Ссылка с логотипом --> <a class="navbar-brand" href="#"> <img src="/images/logo.png" width="50" height="50" alt="..."> </a> .......... </nav>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <!-- Ссылка с логотипом и текстом--> <a class="navbar-brand" href="#"> <img src="/images/logo.png" class="d-inline-block align-top" width="50" height="50" alt="..."> Brand </a> .......... </nav>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <!-- Как заголовок без ссылки--> <span class="navbar-brand mb-0 h1">Brand</span> .......... </nav>
Кнопка для открытия меню
Имеет css-класс и предназначена для показа и скрытия содержимого меню на малениких экранах:
<nav class="navbar navbar-expand-lg navbar-dark bg-dark"> .......... <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-example" aria-controls="navbar-example" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> .......... </nav>
Блок содержимого меню
Имеет css-классы и скрывается в контрольной точке, которая задается классом . Может быть показано и скрыто по клику на кнопке :
<nav class="navbar navbar-expand-lg navbar-dark bg-dark"> .......... <div class="collapse navbar-collapse" id="navbar-example"> .......... </div> .......... </nav>
Блок ссылок меню
Имеет css-класс и состоит из ссылок и вложенных выпадающих списков со ссылками:
<nav class="navbar navbar-expand-lg navbar-dark bg-dark"> .......... <div class="collapse navbar-collapse" id="navbar-example"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#"> Первая ссылка <span class="sr-only">(текущая)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">Вторая ссылка</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Выпадающее меню </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Третья ссылка</a> <a class="dropdown-item" href="#">Четвертая ссылка</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Пятая ссылка</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Не активная</a> </li> </ul> .......... </div> .......... </nav>
Форма внутри меню
<nav class="navbar navbar-expand-lg navbar-dark bg-dark"> .......... <div class="collapse navbar-collapse" id="navbar-example"> .......... <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-info my-2 my-sm-0" type="submit">Search</button> </form> </div> .......... </nav>
Текст внутри меню
Класс — позволяет добавлять текст в меню.
<nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <span class="navbar-brand mb-0 h1">Brand</span> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-example" aria-controls="navbar-example" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbar-example"> <ul class="navbar-nav"> <li class="nav-item">...</li> <li class="nav-item">...</li> <li class="nav-item">...</li> </ul> <!-- Текст внутри меню --> <span class="navbar-text mx-auto">Navbar text with an inline element</span> <form class="form-inline"> .......... </form> </div> </nav>
Поиск:
Bootstrap • CSS • HTML • Web-разработка • Верстка • Компонент • Меню • Навигация • Фреймворк • Navbar
Containers
Containers are the most basic layout element in Bootstrap and are required when using our default grid system. Containers are used to contain, pad, and (sometimes) center the content within them. While containers can be nested, most layouts do not require a nested container.
Bootstrap comes with three different containers:
- , which sets a at each responsive breakpoint
- , which is at all breakpoints
- , which is until the specified breakpoint
The table below illustrates how each container’s compares to the original and across each breakpoint.
See them in action and compare them in our .
Extra small<576px | Small≥576px | Medium≥768px | Large≥992px | Extra large≥1200px | |
---|---|---|---|---|---|
100% | 540px | 720px | 960px | 1140px | |
100% | 540px | 720px | 960px | 1140px | |
100% | 100% | 720px | 960px | 1140px | |
100% | 100% | 100% | 960px | 1140px | |
100% | 100% | 100% | 100% | 1140px | |
100% | 100% | 100% | 100% | 100% |
Responsive
Responsive containers are new in Bootstrap v4.4. They allow you to specify a class that is 100% wide until the specified breakpoint is reached, after which we apply s for each of the higher breakpoints. For example, is 100% wide to start until the breakpoint is reached, where it will scale up with , , and .
Images
SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison Slider
Menus
Icon BarMenu IconAccordionTabsVertical TabsTab HeadersFull Page TabsHover TabsTop NavigationResponsive TopnavNavbar with IconsSearch MenuSearch BarFixed SidebarSide NavigationResponsive SidebarFullscreen NavigationOff-Canvas MenuHover Sidenav ButtonsSidebar with IconsHorizontal Scroll MenuVertical MenuBottom NavigationResponsive Bottom NavBottom Border Nav LinksRight Aligned Menu LinksCentered Menu LinkEqual Width Menu LinksFixed MenuSlide Down Bar on ScrollHide Navbar on ScrollShrink Navbar on ScrollSticky NavbarNavbar on ImageHover DropdownsClick DropdownsDropdown in TopnavDropdown in SidenavResp Navbar DropdownSubnavigation MenuDropupMega MenuMobile MenuCurtain MenuCollapsed SidebarCollapsed SidepanelPaginationBreadcrumbsButton GroupVertical Button GroupSticky Social BarPill NavigationResponsive Header
More
Fullscreen VideoModal BoxesDelete ModalTimelineScroll IndicatorProgress BarsSkill BarRange SlidersTooltipsDisplay Element HoverPopupsCollapsibleCalendarHTML IncludesTo Do ListLoadersStar RatingUser RatingOverlay EffectContact ChipsCardsFlip CardProfile CardProduct CardAlertsCalloutNotesLabelsCirclesStyle HRCouponList GroupList Without BulletsResponsive TextCutout TextGlowing TextFixed FooterSticky ElementEqual HeightClearfixResponsive FloatsSnackbarFullscreen WindowScroll DrawingSmooth ScrollGradient Bg ScrollSticky HeaderShrink Header on ScrollPricing TableParallaxAspect RatioResponsive IframesToggle Like/DislikeToggle Hide/ShowToggle Dark ModeToggle TextToggle ClassAdd ClassRemove ClassActive ClassTree ViewRemove PropertyOffline DetectionFind Hidden ElementRedirect WebpageZoom HoverFlip BoxCenter VerticallyCenter Button in DIVTransition on HoverArrowsShapesDownload LinkFull Height ElementBrowser WindowCustom ScrollbarHide ScrollbarDevice LookContenteditable BorderPlaceholder ColorText Selection ColorBullet ColorVertical LineDividersAnimate IconsCountdown TimerTypewriterComing Soon PageChat MessagesPopup Chat WindowSplit ScreenTestimonialsSection CounterQuotes SlideshowClosable List ItemsTypical Device BreakpointsDraggable HTML ElementJS Media QueriesSyntax HighlighterJS AnimationsGet Iframe Elements
Dropdown Accessibility
To help improve accessibility for people using screen readers, you should
include the following and attributes, when creating a dropdown menu:
Example
<div class=»dropdown»>
<button class=»btn btn-default dropdown-toggle» type=»button» id=»menu1″ data-toggle=»dropdown»>Tutorials
<span class=»caret»></span></button>
<ul class=»dropdown-menu» role=»menu» aria-labelledby=»menu1″>
<li role=»presentation»><a role=»menuitem» href=»#»>HTML</a></li>
<li role=»presentation»><a role=»menuitem» href=»#»>CSS</a></li>
<li role=»presentation»><a role=»menuitem» href=»#»>JavaScript</a></li>
<li role=»presentation» class=»divider»></li>
<li role=»presentation»><a role=»menuitem» href=»#»>About Us</a></li>
</ul>
</div>
For a complete reference of all dropdown options, methods and events, go to our
Bootstrap JS Dropdown Reference.
Images
SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison Slider