Menu with div css

CSS Creating a menu-div-box?

What i am trying to accomplish is to create menu elements that has a touch of style to em, so each link should be inside a div box with a padding 50 px on each side. When i run this, they get clumped up on top of each other. I don’t want to specify a width since the text inside the menu box should determine the size of it automatically. Ex. (50px+text size+50px)

50px space (just green area) | Sample Text | 50px space (just green area) 

4 Answers 4

Maybe this will help (since divs are block displayed elements by default):

Depending on whether you want this menu vertical or horizontal you may also want to add float: left; to div.menulinkboxaround .

As the previous answers suggest, you could put float:left on the menulinkboxaround .

It is difficult to tell from your description the desired effect, I am assuming you want the menu to be horizontal with 50px either side of the links.

With the code you currently have, the hover state only stretches in one direction, also as you are only specifying :hover it is not really as keyboard friendly as it would be if you specified :focus as well.

Also because you are setting the height in px as you increase the font size the text becomes clipped at the bottom. Not specifying the pseudo selectors on the link may also cause you later problems in Internet Explorer.

Читайте также:  Вывести все простые делители числа питон

You could also tidy up the code a little to reduce the unnecessary classes and improve the semantics of the menu.

I have tested this in recent versions of FF, Opera and Safari, and IE6 IE7 and IE8

This second method is much more reliable, deals with wrapping links nicer and is generally a better solution but a bit harder to explain.

If you didn’t want the menu to fill the full width of the screen just as long as the text takes up, regardless of which method you are using above, I suggest you put float: left and clear: both on the ul.menu which should shrink to the width it needs to take up

Источник

How TO — Mega Menu

Learn how to create a mega menu (full-width dropdown menu in a navigation bar).

Mega Menu

Create A Mega Menu

Create a dropdown menu that appears when the user moves the mouse over an element inside a navigation bar.

Step 1) Add HTML:

Example

Home
News

Example Explained

Use any element to open the dropdown menu, e.g. a , or

element.

Step 2) Add CSS:

Example

/* Navbar container */
.navbar overflow: hidden;
background-color: #333;
font-family: Arial;
>

/* Links inside the navbar */
.navbar a float: left;
font-size: 16px;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
>

/* The dropdown container */
.dropdown float: left;
overflow: hidden;
>

/* Dropdown button */
.dropdown .dropbtn font-size: 16px;
border: none;
outline: none;
color: white;
padding: 14px 16px;
background-color: inherit;
font: inherit; /* Important for vertical align on mobile phones */
margin: 0; /* Important for vertical align on mobile phones */
>

/* Add a red background color to navbar links on hover */
.navbar a:hover, .dropdown:hover .dropbtn background-color: red;
>

/* Dropdown content (hidden by default) */
.dropdown-content display: none;
position: absolute;
background-color: #f9f9f9;
width: 100%;
left: 0;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
>

/* Mega Menu header, if needed */
.dropdown-content .header background: red;
padding: 16px;
color: white;
>

/* Show the dropdown menu on hover */
.dropdown:hover .dropdown-content display: block;
>

/* Create three equal columns that floats next to each other */
.column float: left;
width: 33.33%;
padding: 10px;
background-color: #ccc;
height: 250px;
>

/* Style links inside the columns */
.column a float: none;
color: black;
padding: 16px;
text-decoration: none;
display: block;
text-align: left;
>

/* Add a background color on hover */
.column a:hover background-color: #ddd;
>

/* Clear floats after the columns */
.row:after content: «»;
display: table;
clear: both;
>

Example Explained

We have styled the navigation bar and the navbar links with a background-color, padding, etc.

We have styled the dropdown button with a background-color, padding, etc.

The .dropdown-content class holds the actual dropdown menu. It is hidden by default, and will be displayed on hover (see below). It is positioned to be visible right below the dropdown button, and the width is set to 100% to cover the whole screen.

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.

The .column classes are used to create three columns that floats next to each other inside the dropdown menu (to show different categories).

Responsive Mega Menu

Example

/* Responsive layout — makes the three columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) .column width: 100%;
height: auto;
>
>

Tip: Go to our CSS Dropdowns Tutorial to learn more about dropdowns.

Tip: Go to our Clickable Dropdowns to learn more about clickable dropdowns

Tip: Go to our CSS Navbar Tutorial to learn more about navbars.

Tip: Go to our Responsive Top Navigation to learn about how to create a responsive navbar.

Источник

CSS меню

Если ваш веб-сайт не ограничивается одной веб-страницей, то стоит подумать о добавлении панели навигации (меню). Меню — раздел веб-сайта, предназначенный помогать посетителю перемещаться по сайту. Любое меню представляет собой список ссылок, ведущих на внутренние страницы сайта. Самым простым способом добавить панель навигации на сайт является создание меню с помощью CSS и HTML.

Вертикальное меню

Первым шагом создания вертикального меню будет создание маркированного списка. Также нам нужно будет иметь возможность идентифицировать список, поэтому мы добавим к нему атрибут id с идентификатором «navbar». Каждый элемент нашего списка будет содержать по одной ссылке:

Наша следующая задача заключается в сбросе стилей списка, установленных по умолчанию. Нам нужно убрать внешние и внутренние отступы у самого списка и маркеры у пунктов списка. Затем зададим нужную ширину:

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

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

Мы объединили весь код, описанный выше, в один пример, теперь, нажав на кнопку попробовать, вы можете перейти на страницу с примером и увидеть результат:

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

Вернемся к рассмотренному ранее примеру вертикального меню и добавим в таблицу стилей следующее правило:

Горизонтальное меню

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

Для размещения пунктов меню по горизонтали, сначала создадим маркированный список с ссылками:

Напишем для нашего списка пару правил, сбрасывающих стиль используемый для списков по умолчанию, и переопределим пункты списка с блочных на строчные:

Теперь нам осталось лишь определить стилевое оформление для нашего горизонтального меню:

#navbar < margin: 0; padding: 0; list-style-type: none; border: 2px solid #0066FF; border-radius: 20px 5px; width: 550px; text-align: center; background-color: #33ADFF; >#navbar a < color: #fff; padding: 5px 10px; text-decoration: none; font-weight: bold; display: inline-block; width: 100px; >#navbar a:hover

Выпадающее меню

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

Сначала нам нужно создать HTML-структуру нашего меню. Основные навигационные ссылки мы поместим в маркированный список:

#navbar ul < display: none; >#navbar li:hover ul

Убираем у обоих списков отступы и маркеры, установленные по умолчанию. Элементы списка с навигационными ссылками делаем плавающими, формируя горизонтальное меню, но для элементов списка, содержащих подпункты задаем float: none;, чтобы они отображались друг под другом.

#navbar, #navbar ul < margin: 0; padding: 0; list-style-type: none; >#navbar li < float: left; >#navbar ul li

Затем нам нужно сделать так, чтобы наше выпадающее подменю не смещало контент, расположенный под панелью навигации, вниз. Для этого мы зададим пунктам списка position: relative;, а списку, содержащему подпункты position: absolute; и добавим свойство top со значением 100%, чтобы абсолютно позиционированное подменю отображалось точно под ссылкой.

#navbar ul < display: none; position: absolute; top: 100%; >#navbar li < float: left; position: relative; >#navbar

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

Теперь нам осталось стилизовать оба наших списка и выпадающее меню будет готово:

#navbar ul < display: none; background-color: #f90; position: absolute; top: 100%; >#navbar li:hover ul < display: block; >#navbar, #navbar ul < margin: 0; padding: 0; list-style-type: none; >#navbar < height: 30px; background-color: #666; padding-left: 25px; min-width: 470px; >#navbar li < float: left; position: relative; height: 100%; >#navbar li a < display: block; padding: 6px; width: 100px; color: #fff; text-decoration: none; text-align: center; >#navbar ul li < float: none; >#navbar li:hover < background-color: #f90; >#navbar ul li:hover

Копирование материалов с данного сайта возможно только с разрешения администрации сайта
и при указании прямой активной ссылки на источник.
2011 – 2023 © puzzleweb.ru

Источник

How TO — Subnav

Use any element to open the subnav/dropdown menu, e.g. a , or

element.

Use a container element (like ) to create the subnav menu and add the subnav links inside it.

Wrap a element around the button and the to position the subnav menu correctly with CSS.

Step 2) Add CSS:

Example

/* The navigation menu */
.navbar overflow: hidden;
background-color: #333;
>

/* Navigation links */
.navbar a float: left;
font-size: 16px;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
>

/* The subnavigation menu */
.subnav float: left;
overflow: hidden;
>

/* Subnav button */
.subnav .subnavbtn font-size: 16px;
border: none;
outline: none;
color: white;
padding: 14px 16px;
background-color: inherit;
font-family: inherit;
margin: 0;
>

/* Add a red background color to navigation links on hover */
.navbar a:hover, .subnav:hover .subnavbtn background-color: red;
>

/* Style the subnav content — positioned absolute */
.subnav-content display: none;
position: absolute;
left: 0;
background-color: red;
width: 100%;
z-index: 1;
>

/* Style the subnav links */
.subnav-content a float: left;
color: white;
text-decoration: none;
>

/* Add a grey background color on hover */
.subnav-content a:hover background-color: #eee;
color: black;
>

/* When you move the mouse over the subnav container, open the subnav content */
.subnav:hover .subnav-content display: block;
>

Источник

Оцените статью