My Site Home Page SHTML

Как центрировать меню html

Find centralized, trusted content and collaborate around the technologies you use most.

Connect and share knowledge within a single location that is structured and easy to search.

I need to center align a horizontal menu.
I’ve tried various solutions, including the mix of inline-block / block / center-align etc., but haven’t succeeded. Here is my code:

UPDATE I know how to center align the ul within the div . That can be accomplished using Sarfraz’s suggestion. But the list items are still floated left within the ul . Do I need Javascript to accomplish this?

17 Answers 17

The premise is simple and basically just involves a widthless float wrapper that is floated to the left and then shifted off screen to the left width position:relative; left:-50%. Next the nested inner element is reversed and a relative position of +50% is applied. This has the effect of placing the element dead in the center. Relative positioning maintains the flow and allows other content to flow underneath.

Code

#buttons < float:right; position:relative; left:-50%; text-align:left; >#buttons ul < list-style:none; position:relative; left:50%; >#buttons li/* ie needs position:relative here*/ #buttons a < text-decoration:none; margin:10px; background:red; float:left; border:2px outset blue; color:#fff; padding:2px 5px; text-align:center; white-space:nowrap; >#buttons a:hover < border:2px inset blue;color:red;background:#f2f2f2;>#content/* hide horizontal scrollbar*/

The solution works great and I’m sorry to ask this after such a long time, but what if I have a css drop down? I can’t use overflow:hidden in the parent then. But it’ll still overflow like here: homeafrika.com .

Don’t actually see any overflow on that site. I’m not sure you need the overflow: hidden; bit anyways, though since it’s for horizontal overflow, you could always try overflow-x: hidden; instead. webchat.freenode.net/?nick=oerflowono&channels=#websites for real-time assistance.

The solution centers the menu nicely, but if you have submenus that should open at a certain fixed position on hover, you’re doomed since the position: relative of the main menu changes the behavior of the position:absolute of the sub menu.

@reisio Where there is #buttons id in OP’s question? Where there is notice, in your answer, that he have to use it? How can this be accepted and top-voted answer, if you’re actually not answering the question, only citing some off-topic blah-blah from some link?

This works for me. If I haven’t misconstrued your question, you might give it a try.

 div#centerDiv < width: 100%; text-align: center; border: 1px solid red; >ul.centerUL < margin: 2px auto; line-height: 1.4; padding-left: 0; >.centerUL li

This is lovely! But, the ul has default padding on the left which means the menu is nudged to the right of the center. You’ll need to remove the default padding from the ul with padding-left: 0;

Perfectly a better answer than the accepted solution, use of display:inline does the trick. do not use float, its overly complicated. Thanks for the insights @Robusto

Читайте также:  Клиентское приложение java ee

This is the simplest way I found. I used your html. The padding is just to reset browser defaults.

Here’s a good article on how to do it in a pretty rock-solid way, without any hacks and full cross-browser support. Works for me:

Like so many of you, I’ve been struggling with this for a while. The solution ultimately had to do with the div containing the UL. All suggestions on altering padding, width, etc. of the UL had no effect, but the following did.

It’s all about the margin:0 auto; on the containing div. I hope this helps some people, and thanks to everyone else who already suggested this in combination with other things.

.divNav < width: 99%; text-align:center; margin:0 auto; >.divNav ul < display:inline-block; list-style:none; zoom: 1; >.divNav ul li < float:left; margin-right: .8em; padding: 0; >.divNav a, #divNav a:visited

    ) is using the margin:auto; property.

To align text and inline level elements within a block level element use text-align:center; . So all together something like.

The fringe case is Internet Explorer6. or even other IEs when not using a . IE6 incorrectly aligns block level elemnts using text-align . So if you’re looking to support IE6 (or not using a ) your full solution is.

div.topmenu-design < text-align:center; >div.topmenu-design ul < margin:auto; >div.topmenu-design ul li < text-align:center; list-style-position:inside; /* so that the bullet points are also centered */ >div.topmenu-design ul li div < display:inline; /* so that the bullet points aren't above the content */ >

As a footnote, I think id=»topmenu firstlevel» is invalid as an id attribute can’t contain spaces. ? Indeed the w3c recommendation defines the id attribute as a ‘name’ type.

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits (1), hyphens («-«), underscores («_»), colons («:»), and periods («.»).

Источник

Горизонтально центрированное меню с использованием только CSS

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

Пример центрированного меню

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

demosourse

На демонстрационной странице можно увидеть несколько вариантов оформления горизонтально центрированного меню. Любой из них можно использовать в своих проектах.

Разметка HTML

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

Код CSS центрированного меню

Ниже приводится полный код CSS, с помощью которого центрируется меню. А объяснения принципа работы приводятся далее в уроке.

#centeredmenu < float:left; width:100%; background:#fff; border-bottom:4px solid #000; overflow:hidden; position:relative; >#centeredmenu ul < clear:left; float:left; list-style:none; margin:0; padding:0; position:relative; left:50%; text-align:center; >#centeredmenu ul li < display:block; float:left; list-style:none; margin:0; padding:0; position:relative; right:50%; >#centeredmenu ul li a < display:block; margin:0 0 0 1px; padding:3px 10px; background:#ddd; color:#000; text-decoration:none; line-height:1.3em; >#centeredmenu ul li a:hover < background:#369; color:#fff; >#centeredmenu ul li a.active, #centeredmenu ul li a.active:hover

Читайте также:  Python только целое число

Как работает метод центрирования

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

Элемент div без смещения

Элемент div без смещения

Элемент div (блочный) без смещения растягивается на всю доступную ему ширину.

Элемент div со смещением влево

Элемент div со смещением влево

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

Стандартное выровненное влево меню

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

Стандартное меню

Обратите внимание на следующие моменты:

  • Элемент centeredmenu div (голубой прямоугольник) смещается влево, но имеет ширину 100%, поэтому остается растянутым на всю страницу.
  • Элемент ul (розовый прямоугольник) находится внутри элемента centeredmenudiv и смещается влево. Это означает, что он будет ужат до ширины своего содержимого, то есть до суммарной ширины всех закладок.
  • Все элементы li (зеленые прямоугольники) находятся внутри элемента ul и смещаются влево. Таким образом, они ужимаются до размеров ссылок в них и выстраиваются в одну горизонтальную линию.
  • Внутри каждой ссылки (оранжевые прямоугольники) выводится текст закладки: Закладка 1, Закладка 2 и так далее.

Смещаем положение неупорядоченного списка

Смещение неупорядоченного списка

Затем мы смещаем элемент ul вправо на 50% с помощью свойства position:relative; . Когда элемент смещается с указанием процента при таких условиях важно помнить, что суммарная ширина содержащихся в нем элементов не является его шириной. В нашем случае смещение происходит на половину окна браузера (или доступного для вывода пространства).В результате наше меню начинается на середине окна и частично выходит за его пределы. И переходим к следующему шагу.

Сдвигаем положение всех элементов меню

Сдвигаем элементы меню

Осталось только сдвинуть все элементы li влево на 50%. Это 50% ширины нашего элемента ul (контейнера, который содержит меню). Таким образом, закладки смещаются точно на центр окна.

Несколько важных замечаний

При использовании данного метода центрирования надо помнить о нескольких важных моментах:

  • Так как элемент ul частично выходит за рамки окна, то это приводит к выводу полос прокрутки. Поэтому нужно использовать правило overflow:hidden; для элемента centeredmenu div. Таким образом, выступающая часть элемента div будет обрезана.
  • Так как элемент ul не выровнен по закладкам, то нельзя использовать никаких визуальных стилей для него. Оставьте элемент ul без фонового цвета и без рамки, чтобы он стал полностью невидимым. А стили для закладок нужно использовать только для элементов li.
  • Если нужно задать особенные стили для первой и последней закладки, нужно добавить класс для первого и последнего элементов li, чтобы можно было стилизовать их индивидуально.

Заключение

Предложенное решение совместимо со всеми браузерами, не использует JavaScript и поддерживает изменяемый размер текста.

Источник

CSS how to center a menu

I can’t get a menu to be centered. I have images, etc. that center just fine, but I can’t center the menu. Here’s some of the site’s CSS that pertains to the menu:

@charset "UTF-8"; /* CSS Document */ #nav < width:975px; /* six main menu buttons at 150px per */ margin:1 auto; /* Based on a suggestion from stackoverflow */ list-style-type:none; text-align:center; position: fixed; /* used to render menu bar on top */ top: 0; /* used to render menu bar on top */ z-index: 1000; /* use z-index to render menu bar on top of everything, even the slideshow */ display:inline-block; >#nav li < display:inline-block; /* used to wrap text */ position:relative; float:left; background-color: #BDB76B; /* menu background color */; font-family: Arial, Helvetica, sans-serif; font-size:14px; >#nav li:hover < /* highlights current hovered list item when hovering over the parent menu */ background-color:#BDB76B; font-weight:500; color:blue; >#nav li a < display:inline-block; /* used to wrap text */ margin:5px 0; /*space between menu elements */ text-decoration:none; width:150px; /* this is the width of the menu items */ line-height:15px; /* this is the text height of the menu items */ color:#000000; /* list item font color 000=black, FFF=white*/ >#nav li a:hover < /* highlights hovered item of the parent menu */ background-color:#BDB76B; font-weight:500; color:blue; font-size:18px; width:225px; >#nav li li a < /* smaller font size for sub menu items */ font-size:90%; background-color: #BDB76B; /* menu background color for submenues */ >#nav li li a:hover < /* highlights current hovered list when hovering over sub menues */ background-color:#BDB76B; font-weight:500; color:blue; font-size:120%; width:200px; >/*--- Sublist Styles ---*/ #nav ul < position:absolute; padding:0; left:0; display:none; /* hides sublists */ >#nav li:hover ul ul < display:none; >/* hides sub-sublists */ #nav li:hover ul < display:block; >/* shows sublist on hover */ #nav li:hover ul ul ul < display:none; >/* hides sub-sub-sublists */ #nav li li:hover ul < display:block; /* shows sub-sublist on hover */ margin-left:150px; /* this should be the same width as the parent list item */ margin-top:-35px; /* aligns top of sub menu with top of list item */ >#nav li li li:hover ul < display:block; /* shows sub-sub-sublist on hover */ margin-left:150px; /* this should be the same width as the parent list item */ margin-top:-35px; /* aligns top of sub menu with top of list item */ width:200px; >.upcoming_events_list li < /* attributes for the upcoming_events list level */ /* CSS to alter the links in the include list when inside the div */ width: 380px; text-align: left; list-style-type:circle; color:blue; >.upcoming_events_list li a:link < /* attributes for the upcoming_events unvisited */ font-family: "Times New Roman", Times, serif; color: black; font-size: 18px; font-weight: 300; list-style-type: circle; >.upcoming_events_list li a:visited < /* attributes for the upcoming_events visited */ font-family: "Times New Roman", Times, serif; color: blue; font-size: 18px; font-weight: 100; list-style-type: circle; >.upcoming_events_list li a:hover < /* attributes for the upcoming_events hover */ font-family: "Times New Roman", Times, serif; font-size: 20px; font-weight: 500; >.upcoming_events_list li a:active < /* attributes for the upcoming_events selected */ font-family: "Times New Roman", Times, serif; font-size: 20px; font-weight: 500; text-decoration: underline; >

                  

Parish Site

Источник

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