2017-02-05 16 views
2

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

Я также попытался использовать @media, чтобы заставить ширину до 70% всего окна. Вместо этого это повлияло только на окно компьютера. Я использовал максимальную ширину и задал ее до 1200 пикселей. Кажется, он ничего не делает. Я даже попробовал добавить переполнение: скрытый, чтобы предотвратить возможное изменение размера, если что-то уклонилось от границ.

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

Вот JSFiddle замарать: https://jsfiddle.net/Shadowfang/Lc5Ljaf4/

Update: L L оставил меня с какой-то код, который я использовал, чтобы изменить мою JSFiddle. Он решил проблему с исчезновением навигационной панели с экрана. Он также отлично изменяется, пока вы не сможете сжать окно дальше. Однако у меня все еще есть некоторые изменения, которые нужно сделать, чтобы исправить внешний вид и вернуть меню обратно в горизонтальное положение. Вот новый один: https://jsfiddle.net/Shadowfang/Lc5Ljaf4/13/

HTML:

<!DOCTYPE html> 
<html lang="en"> 

<head> 
    <title>The Den</title> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0" /> 
    <link rel="stylesheet" media="screen, projection" href="style.css"> 
    <script type ="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> 
    <script type ="text/javascript" src="script.js"></script> 
</head> 

<body> 
    <!-- It would be nice to know if tables are what's throwing off my entire website or not... but whatever. --> 
    <div class="status"></div> 
    <div class="logo"><!--I'll change the word "container" to Logo perhaps in the future here if I can get this example to work for once. Also let it be noted that I am in fact not using the "header" tag at any portion during this... which is bothersome. -->   
     <center><a href="http://www.wolvesofthedust.com/"><img src="http://i1288.photobucket.com/albums/b494/ShadowfangInnovia/WolvesoftheDustSiteHeader_zpsdddba823.png" height="auto" width="100%" border="0" alt=" photo WolvesoftheDustSiteHeader_zpsdddba823.png"/></a></center> 
    </div> 
    <div class ="navigation"> 

     <!-- The navigation portion... dear God... here is where it all usually goes wrong. --> 
     <nav> 
      <ul class="clearfix"> <!-- Clearfix?! Really?! I'm ASSUREDLY changing that one. --> 
       <li><a href="#">Link 1</a></li> 
       <li><a href="#">Link 2</a></li> 
       <li><a href="#">Link 3</a></li> 
       <li><a href="#">Link 4</a></li> 
       <li><a href="#">Link 5</a></li> 
       <li><a href="#">Link 6</a></li> 
       <li><a href="#">Link 7</a></li> 
       <li><a href="#">Link 8</a></li> 
       <li><a href="#">Link 9</a></li> 
      </ul> 
     </nav><!-- End the hiddeously named section... and hopefully begin progress towards a complete page... --> 
    </div> 
    <div class ="logo2"> 
    </div> 
    <div class ="content"> 
     <br/><br/> 
     <center><h2>THIS WEBSITE IS UNDER CONSTRUCTION!!! TAKE NOTHING HERE YOU SEE SERIOUSLY FOR THE TIME BEING!!!</h2></center> <!-- This is where I will likely have the table located with nicely written dialogue... but if the table isn't needed above then I may as well continue this practice elsewhere. Did I learn all about tables and arranging code properly for nothing? --> 
     <br/> 
     <br/> 
     <p><!-- Interestingly enough it took me a while to realize that P stood for paragraph... considering people normally only wrote a single sentance per line with a "p" tag. Stupid examples and my insinuations based on them -->The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 
     <p>The lazy dog jumped over the quick brown fox. Yes I just did that. Deal with it. This is my website after all.</p> 

    </div> 

CSS:

html { 
    padding: 0; 
    margin: 0; 
    background-color: #000; 
} 

body { 
    font-family: Helvetica, sans-serif; 
    font-size: 93%; 
    line-height: 1.5em; 
    padding: 40px 0; 
    margin: 0; 
    color: #7d0000; 
} 

a, 
a:link, 
a:visited { 
    color: blue; 
} 

h1, h2, h3, h4, h5, h6 {margin-top: 0;} 

p {margin: 0 0 1em 0;} 

.logo { 
    max-width: 940px; 
    margin: 0 auto; 
    padding: 0 20px; 
} 

.navigation { 
    max-width: 100%; 
    margin: 0 auto; 
    padding: 0 20px; 
} 

.logo2 { 
    max-width: 100%; 
    margin: 0 auto; 
    padding: 0 20px; 
} 

.content { 
    max-width: 100%; 
    margin: 0 auto; 
    padding: 0 20px; 
} 

h1 { 
    background-color: #305782; 
    color: #FFF; 
    padding: 60px 25px; 
    margin: 0; 
} 

nav { 
    z-index: 500; 
    background-color: #000; 
} 

.nav-placeholder { 
    margin: 0 0 40px 0; 
} 

.fixed { 
    position: fixed; 
    top: 0; 
    left: 0; 
    width: 100%; 
    background-color: #000; 
} 

.fixed .nav-inner { 
    padding: 0 20px; 
} 

.fixed .nav-inner-most { 
    max-width: 100%; 
    margin: 0 auto; 
    background-color: #000; 
} 

nav ul { 
display: table; 
width: 100%; 
list-style: none; 
padding: 0; 
margin: 0; 
} 

nav ul li { 
display: table-cell; 
text-align: center; 
} 

nav ul li a:link, 
nav ul li a:visited { 
    display: block; 
    text-decoration: none; 
    padding: 10px 25px; 
    background-color: #000; 
    border: 2px solid #7d0000; 
    color: #7d0000; 
    font-size: 90%; 
    font-weight: bold; 
} 

nav ul li a:hover { 
    background-color: #28bfa1; 
    color: #FFF 
} 

@media (min-width: 1200px) { 
    .container{ 
     max-width: 70%; 
    } 
} 

/* This seems to have an undesired effect, but may be necessary for later. 
    The border-right: none; attribute is especially annoying... 

nav ul li:last-child a:link, 
nav ul li:last-child a:visited { 
    border-right: none; 
} 

*/ 

.clearfix:before, .clearfix:after { content: ""; display: table; } 
.clearfix:after { clear: both; } 
.clearfix { *zoom: 1; } 

JS:

jQuery(document).ready(function() { 

    // define variables 
    var navOffset, scrollPos = 0; 

    // add utility wrapper elements for positioning 
    jQuery("nav").wrap('<div class="nav-placeholder"></div>'); 
    jQuery("nav").wrapInner('<div class="nav-inner"></div>'); 
    jQuery(".nav-inner").wrapInner('<div class="nav-inner-most"></div>'); 

    // function to run on page load and window resize 
    function stickyUtility() { 

     // only update navOffset if it is not currently using fixed position 
     if (!jQuery("nav").hasClass("fixed")) { 
      navOffset = jQuery("nav").offset().top; 
     } 

     // apply matching height to nav wrapper div to avoid awkward content jumps 
     jQuery(".nav-placeholder").height(jQuery("nav").outerHeight()); 

    } // end stickyUtility function 

    // run on page load 
    stickyUtility(); 

    // run on window resize 
    jQuery(window).resize(function() { 
     stickyUtility(); 
    }); 

    // run on scroll event 
    jQuery(window).scroll(function() { 

     scrollPos = jQuery(window).scrollTop(); 

     if (scrollPos >= navOffset) { 
      jQuery("nav").addClass("fixed"); 
     } else { 
      jQuery("nav").removeClass("fixed"); 
     } 

    }); 

}); 

Спасибо заранее,

Темного

ответ

1

Как упоминался в комментариях к скрипке, таблицы действительно то, что бросают свой веб-сайт, или по крайней мере, этой части коды:

nav ul li { 
display: table-cell; 
text-align: center; 
} 

Вы должны изменить дисплей встроенного блока для пример. Сразу же у вас будет гораздо более отзывчивое поведение, и ничто не упадет с экрана. Для этого потребуется несколько дополнительных изменений css, чтобы они выглядели хорошо, например удаление отступов для элементов внутри элементов li в меню. По мере того, как экран сжимается, элементы меню, которые будут выходить из экрана, теперь перейдут в новую строку. Если вы хотите этого избежать, вы можете установить фиксированную ширину в%. Глядя на ваш код заставляет меня думать, что этого должно быть достаточно, чтобы вы пошли, дайте мне знать, если это поможет.

+0

На самом деле, вы помогли тонну. Самая большая головная боль заключалась в том, что он заставил себя покинуть экран. Я обновил JSFiddle, чтобы показать его текущее состояние. Я хотел бы вернуть меню в горизонтальное положение, не теряя центровки. Все остальное работает отлично. Вопреки тому, как это может показаться, я на самом деле очень новичок в этом. Так что спасибо за терпение. Я также обновил JSFiddle. – Shadowfang

+0

@L L В его нынешнем виде навигационная панель хочет оставить влево, если я удалю атрибут width из 'nav ul li', но оставив его, навигационная панель остается вертикальной. Я не совсем уверен, как это исправить. Но как только эта проблема будет решена, я помету ваш ответ как полный, так как он исправил все, что я спросил выше. – Shadowfang

+0

Это то, что я добавил бы: 'nav ul li {margin: 5px; display: inline-block}', а также 'nav ul {text-align: center;}'.Это похоже на самый простой способ получить приемлемое поведение при изменении размера окна, а также в обычном режиме. Вот скрипка https://jsfiddle.net/jtg6vtz4/ –

 Смежные вопросы

  • Нет связанных вопросов^_^