Nano Hash - криптовалюты, майнинг, программирование

Отзывчивое меню Mobile Bootstrap, движущееся содержимое

Используя Bootstrap, я создал меню NAV. Меню отлично работает на широких экранах, но когда мобильное свернутое меню активировано и вы щелкаете меню, чтобы открыть его, содержимое, содержащееся в строке с классом moves_down_with_menu, перемещается вниз вместе с меню. Я бы предпочел, чтобы строка не менялась при открытии меню. Я просто хочу, чтобы меню прошло мимо него. Тем не менее, я также хочу, чтобы он работал точно так же, как обычно.

Как мне это сделать?

http://jsfiddle.net/k98Bn/65/ — пример того, что он делает.

EDITED: Добавлены разные разделы

<section id='topbar'>
   <p> A black top bar with a message </p>
</section>
<section id='secondsection'>
<div id="hero" >
    <div class="jumbotron">
            <%= render 'shared/nav/nav_pages' %>
        <div class="container">
            <div class="row moves_down_with_menu">
                <div class="col-md-6 col-md-offset-3 marketing">
                    <h1>Some Title Test for display</h1>
                    <div id="heroform">
                        <%= render partial: 'shared/get_form', locals: {:get_form => get_form} %>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</section>
<section id='thirdsection' >
</section>

  • Ваш вопрос не очень ясен. Было бы полезно иметь JSFiddle, демонстрирующий проблему. 02.01.2017
  • Пожалуйста, опубликуйте минимальный полный проверяемый пример вашего кода, отображающего проблему. 02.01.2017
  • @RunnyYolk Пожалуйста, смотрите Jsfiddle 02.01.2017

Ответы:


1

Вы можете добавить position: absolute на свою панель навигации (вам, скорее всего, потребуется изменить высоту и отступы, связанные с вашим первым Jumbotron).

абсолютно

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

Дополнительную информацию см. в разделе Position на MDN.

Пример CSS:

.navbar {
  background: transparent;
  position: absolute;
  width: 100%;
  z-index: 1500;
}

В качестве альтернативы вы можете добавить класс Bootstrap navbar-fixed-top в свой блок навигации ( ваша панель навигации будет прокручиваться вместе со страницей.)

.navbar.navbar-inverse {
  background: transparent;
  position: absolute;
  width: 100%;
  z-index: 1500;
}
#hero .jumbotron {
  background: blue;
  height: 325px;
  margin: 0;
}
#hero .jumbotron .marketing {
  padding-top: 50px;
}
#part2 .jumbotron {
  background: red;
  padding: 20px;
  margin: 0;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div id="hero">
  <div class="jumbotron">

    <div class="navbar navbar-inverse">
      <div class="container">

        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Bootstrap 3.0 Skeleton</a>
        </div>

        <div class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#">Home</a>
            </li>
            <li><a href="#about">About</a>
            </li>
            <li><a href="#contact">Contact</a>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <div class="container">
      <div class="row moves_down_with_menu">
        <div class="col-md-6 col-md-offset-3 marketing">
          <h1>Some Title Test for display</h1>
          <div id="heroform">
            <p>
              This should not move with menu open
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<section id='part2'>
  <div class='jumbotron'>
    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer
      took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset
      sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the
      industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially
      unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy
      text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five
      centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like
      Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type
      and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing
      Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard
      dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
      It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the
      printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,
      but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker
      including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled
      it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum
      passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text
      ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised
      in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting
      industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into
      electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions
      of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
      specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more
      recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
      when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s
      with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry.
      Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic
      typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem
      Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
      book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
      with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </div>
</section>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

02.01.2017

2

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

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

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

Надеюсь, на этот раз у вас получится лучше! ссылка на codepen https://codepen.io/stevebennn/pen/1f445118e4d8dbdec13149c0defd1197

.navbar {
  position: absolute;
  width: 100%;
  top: 0;
  z-index: 1
}

.jumbotron {
  width: 100%;
  height: 100%;
  background: #00bcd4;
}

.relative-container {
  position: relative;
}

.margin-nuke {
  margin: 0;
}

.content-container {
  top: 50px; /* this is the height of the navbar. you should make it a variable so you know they are always the same :)*/
  background: #e3e;
  width: 100%;
}

02.01.2017
  • Спасибо, и если бы мое навигационное меню было верхней панелью, я бы согласился. Однако на самом деле он находится в другом разделе, поэтому я не уверен, как с этим справиться. 02.01.2017
  • так что вы ищете | jumbotron/hero › nav › content-area | с этой структурой вы не хотите, чтобы навигация перемещала область содержимого. правильный? 03.01.2017
  • Я обновил приведенный выше пример... дайте мне знать, если это то, что вы искали 03.01.2017
  • В моем случае у джамботрона есть изображение, а меню Nav содержится в джамботроне. Этот пример разделил их. Я изменил свой код и добавил минимальную высоту, чтобы jumbotron мог расти вместе с меню, а не оставаться фиксированным, и это кажется нормальным, но не совсем тем решением, которое я хотел. 05.01.2017
  • Новые материалы

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

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

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

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

    Работа с векторными символическими архитектурами, часть 4 (искусственный интеллект)
    Hyperseed: неконтролируемое обучение с векторными символическими архитектурами (arXiv) Автор: Евгений Осипов , Сачин Кахавала , Диланта Хапутантри , Тимал Кемпития , Дасвин Де Сильва ,..

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

    Обеспечение масштабируемости LLM: облачный анализ с помощью AWS Fargate и Copilot
    В динамичной области искусственного интеллекта все большее распространение получают модели больших языков (LLM). Они жизненно важны для различных приложений, таких как интеллектуальные..