HTML

How to center navbar with CSS?

The navbar is used to navigate to the pages on the website. It contains the links to the pages. The navbar can be aligned to the center, left, or right using CSS properties. Here, we will learn how to center the navbar.

Center the navbar

We can center the navbar using margin: auto property. It will create equal space to the left and right to align the navbar to the center horizontally. Additionally, add the width of the navbar.

Example: Centering the navbar with CSS.

    /* Add a black background color to the top navigation */ .navbar < background-color: #CCCCCC; overflow: hidden; width: 700px; margin: auto; >/* Style the links inside the navigation bar */ .navbar a < float: left; color: black; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 20px; >h2  
Home About Contact

Here we have successfully centered a navbar

Output

Here is the output of the above program.

center the navbar

Example: Center the nav with CSS

We can set the width of the navbar so that the navbar centers at a particular viewport width.

Conclusion

In this tutorial, we have learned to center the navbar with CSS. We used the margin: auto property to center the navbar. See the examples to know more about the code.

Источник

Выравнивание навигации по страницам

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

Такая навигация обычно формируется посредством не маркированного списка — тег ul, элементы которого являются блочными контейнерами — li. Так как наши новости постепенно добавляются, то мы не можем определять их точное количество, в таком случае нам нужно универсальное решение. Чтобы установить элементы навигации в одну строку — воспользуемся свойством float. Расположить этот блок логичнее всего будет по центру экрана, как это показано в примере

Пример навигации на сайте

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

div class="navigation"> ul> li>1li> li>a href="#">2a>li> li>a href="#">3a>li> li>a href="#">4a>li> ul> div>
.navigation  width: 100%; text-align: center; /*пробуем центровать навигацию*/ padding: 20px 0; background: #63beef; float: left; > ul  list-style: none; font-size: 12px; margin: 0 auto; padding: 0; > li  float: left; /*блочные элементы в 1 строку*/ margin-right: 4px; width: 23px; height: 19px; overflow: hidden; text-align: center; color: #63beef; font-weight: bold; position: relative; background:#ddf3ff; cursor: default; padding-top: 3px; border-radius:50%; > li a  color: #63beef; text-decoration: none; position: absolute; top: 0; left: 0; display: block; background:#fff; text-align: center; width: 23px; height: 22px; padding-top: 3px; >

В примере этого кода мы попробовали выровнять блок с навигацией стандартным способом, используя для дочернего элемента свойство text-align. Однако, если прогоним наш код через браузер, то убедимся, что традиционное центрование не срабатывает. Это происходит из-за того, что ширина блока четко не определена.

Неудачный пример выравнивания навигации

Решение возникшей проблемы

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

div class="navigation"> span> ul> li>1li> li>a href="#">2a>li> li>a href="#">3a>li> li>a href="#">4a>li> ul> span> div>
.navigation  width: 100%; text-align: center; padding: 20px 0; background: #63beef; float: left; > ul  display: table; /* это определит зависимость ширины от содержимого */ width: auto; margin: 0 auto; list-style: none; font-size: 12px; padding: 0; > * html .navigation span /*хак для IE*/ display: inline-block; > *:first-child+html .navigation span /*хак для IE*/ display: inline-block; > li  float: left; /*блочные элементы в 1 строку*/ margin-right: 4px; width: 23px; height: 19px; overflow: hidden; text-align: center; color: #63beef; font-weight: bold; position: relative; background:#ddf3ff; cursor: default; padding-top: 3px; border-radius:50%; > li a  color: #63beef; text-decoration: none; position: absolute; top: 0; left: 0; display: block; background:#fff; text-align: center; width: 23px; height: 22px; padding-top: 3px; >

По итогу получаем навигацию по центру страницы, как показано на рисунке

Выравнивание навигации по центру страницы

Из кода видно, что проблемная ситуация с IE снова повторяется, впрочем, ничего удивительного. Единственное, что следует отметить по этому поводу, это то, что в реальных условиях при использовании такого кода, костыли для старичка нужно вставлять через условные комментарии.

Также следует отметить серьезный недостаток этого метода. Наш код не сможет пройти проверку на влидацию, так как, в соответствии со спецификацией, строчный элемент не должен содержать в себе блочные теги. Замена вспомогательного строчного элемента span на блочный не допустима, так как IE не переопределит навигацию в центре страницы в таком случае.

Валидное решение

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

div class="navigation"> span> ul> b>1b> a href="#">2a> a href="#">3a> a href="#">4a> ul> span> div>
.navigation  width: 100%; text-align: center; padding: 20px 0; background: #63beef; > span  display: table; width: auto; margin: 0 auto; font-size: 12px; padding: 0; > * html .navigation span /*хак для IE*/ display: inline-block; > *:first-child+html .navigation span /*хак для IE*/ display: inline-block; > a, b  float: left; /*блочные элементы в 1 строку*/ margin-right: 4px; width: 23px; height: 19px; overflow: hidden; text-align: center; color: #63beef; font-weight: bold; position: relative; background:#ddf3ff; cursor: default; padding-top: 3px; border-radius:50%; display: inline; text-decoration:none; >

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

Альтернативное решение без вспомогательных тегов и валидным кодом

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

Итак, это решение не нуждается в вспомогательных тегах для определения ориентации по центру. В тоже время код можно назвать семантичным и с валидацией тоже не возникает никаких проблем. Мы просто берем наш блочный не маркированный список и присваиваем ему свойство строчного элемента, воспользовавшись значением inline-block свойства display:

div class="navigation"> ul> li>1li> li>a href="#">2a>li> li>a href="#">3a>li> li>a href="#">4a>li> ul> div>
.navigation  width: 100%; text-align: center; padding: 20px 0; background: #63beef; > ul  display: inline-block; //display: inline; /*для IE*/ zoom: 1; /*присваиваем ему layout*/ list-style: none; font-size: 12px; padding: 0; > li  float: left; /*блочные элементы в 1 строку*/ display: inline;/*для IE*/ margin-right: 4px; width: 23px; height: 23px; overflow: hidden; text-align: center; color: #63beef; font-weight: bold; background:#ddf3ff; cursor: default; border-radius:50%; line-height: 23px; > li a  color: #63beef; text-decoration: none; display:block; background:#fff; text-align: center; width: 23px; height: 23px; >

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

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

В каких браузерах работает?

Источник

How TO — Centered Top Navigation

Learn how to create a navigation bar with a centered link/logo.

Create a Top Navigation Bar

Step 1) Add HTML:

Example

Step 2) Add CSS:

Example

/* Add a black background color to the top navigation */
.topnav position: relative;
background-color: #333;
overflow: hidden;
>

/* Style the links inside the navigation bar */
.topnav a float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
>

/* Change the color of links on hover */
.topnav a:hover background-color: #ddd;
color: black;
>

/* Add a color to the active/current link */
.topnav a.active background-color: #04AA6D;
color: white;
>

/* Centered section inside the top navigation */
.topnav-centered a float: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
>

/* Right-aligned section inside the top navigation */
.topnav-right float: right;
>

/* Responsive navigation menu — display links on top of each other instead of next to each other (for mobile devices) */
@media screen and (max-width: 600px) .topnav a, .topnav-right float: none;
display: block;
>

.topnav-centered a position: relative;
top: 0;
left: 0;
transform: none;
>
>

Tip: To create mobile-friendly, responsive navigation bars, read our How To — Responsive Top Navigation tutorial.

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

Источник

How do I center the navbar elements?

Add the align attribute to the «nav» tag and give it the value «center».

someone has already edited it!! The person has added ‘text-align=center’ to the ul element in the css stylesheet which is yet another solution to your problem.

Here is Your markup and css for navbar elements.

 .navbar .nav, .navbar .nav > li < float:none; display:inline-block; *display:inline; /* ie7 fix */ *zoom:1; /* hasLayout ie7 trigger */ vertical-align: top; >.navbar-inner
body < position: relative; height: 100vh; width: 100vw; >.navbar < background-color: #000000; position: absolute; top: calc(50% - 3em); border: 3px ridge red; border-radius: 12px; height: 6em; margin: 0 auto; width: 100%; >.linx < display: table; color: #808080; list-style-type: none; text-align: center; width: 100%; overflow: hidden; padding: 1.5em .25em; >.linx > li < display: table-cell; color: #808080 !important; vertical-align: middle; font-size: 1.5em; line-height: 2; text-align: center; >a < color: #FFF !important; >a:hover < color: red !important; text-decoration: none !important; outline: 3px solid red; >.whole

Could work with display: inline; and then just set a padding-right to it.

Here are two examples that might help you. One distributes the links evenly across the container and the other centers the ul .

.navbar.navbar-inverse .navbar-nav > li > a:hover < color: red; >@media (min-width: 768px) < .navbar.navbar-inverse .navbar-nav < display: table; width: 100%; >.navbar.navbar-inverse .navbar-nav > li < display: table-cell; float: none; >.navbar.navbar-inverse .navbar-nav > li > a < text-align: center; >>
.navbar.navbar-inverse .navbar-nav > li > a:hover < color: red; >.navbar.navbar-inverse .navbar-nav < display: inline-block; float: none; vertical-align: top; >.navbar.navbar-inverse .navbar-collapse

Not sure of the ask, but do you want the navbar list items centered in a single row, like below?

enter image description here

To do so, make the rule for the ul li list more specific, and change the display to inline-block, like so:

What it does is override the default .navbar and .navbar-fixed-top ui li properties in the core Bootstrap. Without the .navbar-fixed-top added, the default core Bootstrap CSS is more specific, and thus is a higher priority.

Источник

Center navigation bar with CSS

I am trying to center my nav bar. I checked my sites but nothing works and I’m completely stumped as to why it won’t center, here is my navigation bar HTML that I want to center:

* < margin:0; padding:0; outline:0; >.nav < width:950px; height:auto; border-bottom:1px solid #eee; margin:10px auto 5px; display:inline-block; >.menu < width:auto; list-style:none; font:$pagenavifont; text-align:center; margin:0 auto; >.menu a < float:left; color:#999; text-decoration:none; text-transform:uppercase; width:auto; line-height:36px; padding:0 20px; >.menu a:hover,li.menuhover a < color:#111; >.menu li < position:relative; float:left; width:auto; >.menu li:last-child < background:none; >.menu ul < display:none; position:absolute; top:36px; left:0; background:#fbfbfb; display:none; list-style:none; >.menu ul li < float:none; border-top:1px solid #e3e3e3; border-right:1px solid #e3e3e3; border-left:1px solid #e3e3e3; width:auto; background:none; >.menu ul li:last-child < border-bottom:1px solid #e3e3e3 >.menu ul li a < float:none; display:block; background:none; line-height:36px; min-width:137px; width:auto; text-align:left; padding-left:10px; color:#444; >.menu ul li a:hover

I would give you a link to the page but it’s being done in Dreamweaver and is not up yet. The logobar.jpg is the logo for the webpage. I love how it looks, but it needs to be centered and not be cut off or taken to the next line when I shrink my screensize. I tried each of float: right , float: left , and float: none on almost all of the classes; text-align: center on each class on the html side; I have tried align=center on each class; display: inline , inline-block on ul and li classes. Thank you for your help!

Источник

Читайте также:  Remove all thread java
Оцените статью