Я не совсем знал, с чего начать с существующего кода, поэтому вместо этого я собрал рабочий образец с нуля.Обратите внимание, что приведенный пример является очень простым и является лишь одним из способов достижения поставленной цели.Я проверил его на Firefox 3.6 и больше ничего.Вероятно, существуют проблемы с совместимостью между браузерами, особенно с псевдоклассом :hover
в Internet Explorer.Идея этого кода состоит в том, чтобы просто дать вам простую структуру, с которой можно работать.
Я настоятельно рекомендую вам ознакомиться со следующими статьями, поскольку в них объясняется использование вложенных списков, проблемы с кроссбраузерностьюсовместимость, решения Javascript для проблемы :hover
псевдокласса IE и проблемы доступности со скрытыми элементами с использованием display: none
:
Раскрытия Suckerfish
http://www.alistapart.com/articles/dropdowns
Раскрытие Son of Suckerfish
http://www.htmldog.com/articles/suckerfish/
Скрытие с помощью CSS: проблемы и решения
http://www.456bereastreet.com/archive/200905/hiding_with_css_problems_and_solutions/
Хорошо, на код.Во-первых, HTML.Здесь я использовал вложенные неупорядоченные списки для создания структуры меню.Это хороший способ, так как навигационное меню - это просто вложенный список ссылок.Это будет отображаться правильно для тех, кто не использует CSS, и будет правильно читаться программами чтения с экрана.
Возможно, вы захотите изучить способы удаления ссылок с активной страницы.Например, если активной страницей является страница 1-3, вы можете заменить тег a
на тег span
.
HTML должен быть достаточно понятным.Просто дайте активному меню UL класс active
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<link rel="stylesheet" type="text/css" href="test.css" media="screen" />
<title>Horizontal Menus</title>
</head>
<body>
<div id="topnav">
<ul>
<li>Menu 1
<ul class="active">
<li><a href="#">Page 1-1</a></li>
<li><a href="#">Page 1-2</a></li>
<li><a href="#">Page 1-3</a></li>
<li><a href="#">Page 1-4</a></li>
</ul>
</li>
<li>Menu 2
<ul>
<li><a href="#">Page 2-1</a></li>
<li><a href="#">Page 2-2</a></li>
<li><a href="#">Page 2-3</a></li>
<li><a href="#">Page 2-4</a></li>
<li><a href="#">Page 2-5</a></li>
</ul>
</li>
</ul>
</div>
</body>
</html>
CSS полон комментариев, поэтому он должен быть довольно простым для понимания.Я думаю, что самой сложной частью является правильное форматирование и создание подменю горизонтальным, а не вертикальным.Вы справились с этим, поэтому все остальное должно быть довольно просто:
/*
* The contain DIV for the navigation menu.
* Use this to position the menu on the page.
*/
#topnav {
/*
* Set the containing DIV position to
* relative. This allows the UL to be
* positioned relative to this container.
* See static, relative and absolute, here:
* http://www.w3.org/TR/CSS2/visuren.html#choose-position
*/
position: relative;
}
/*
* All ULs (first and second level).
*/
#topnav ul {
/*
* Remove bullets from the UL.
*/
list-style: none;
/*
* Zero margins and padding.
*/
margin: 0;
padding: 0;
/*
* Take the UL out of the normal flows so
* that it can be given absolute positioning
* coordinates, relative to its containing
* block (the #topnav DIV).
*/
position: absolute;
/*
* Align the UL with the left of the #topnav DIV.
*/
left: 0;
/*
* The list must be wide enough to enclose all
* second level list items (5 x 10em).
*/
width: 50em;
/*
* Give the UL height and a background colour.
* This enables the UL that is activated during a
* hover to mask the UL that is active. See
* the active and hover z-index settings.
*/
height: 1.5em;
background: #eeeeee;
}
/*
* All LIs (first and second level).
*/
#topnav li {
/*
* Float the LIs left so that they all
* appear on one line.
*/
float: left;
/*
* Set the width of each LI.
*/
width: 10em;
}
/*
* Second level UL.
*/
#topnav ul ul {
/*
* Hide all second level LIs.
* Set their position to absolute, then
* move them left by 999em.
*/
position: absolute;
left: -999em;
}
/*
* Second level UL.
* Selected when first-level LI is hovered over,
* or when first-level UI has the 'active' class.
*/
#topnav ul li:hover ul, #topnav ul ul.active {
/*
* Show active LIs.
* Reset the left position to zero.
*/
left: 0;
}
/*
* Second level UL.
* Selected when first-level LI is hovered over.
*/
#topnav ul li:hover ul {
/*
* Set the stacking level (z-index) so that it is
* above the active UL.
*/
z-index: 200;
background: #cccccc;
}
/*
* Second level UL.
* Selected when first-level UI has the 'active' class.
*/
#topnav ul ul.active {
/*
* Set the stacking level (z-index) so that it is
* below the UL that is displayed during hover.
*/
z-index: 100;
background: #aaaaaa;
}
Удачи!