Bootstrap 4 sidenav на мобильном телефоне не слева

Привет. В моем проекте у меня есть левая боковая панель с элементами меню. Мой боковой код:

html {
    height: 100%;
}

body {
    min-height: 100vh;
}

/* fixed and fluid only on sm and up */
@media (min-width: 768px) {
    .fixed {
        flex: 0 0 200px;
        min-height: 100vh;
        min-width: 180px;
    }
    .col .fluid {
       min-height: 100vh;
    }
    .flex-grow {
       flex:1;
    }
}
<html>

<head>
<link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity = "sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin = "anonymous">
</head>

<body>
<div class = "container-fluid h-100">
    <div class = "row h-100">
        <!-- left sidebar -->
        <div class = "col-md-2 fixed pl-0 py-3 bg-light">
            <ul class = "nav flex-md-column flex-nowrap justify-content-center">
                <li class = "nav-item">
                    <a class = "nav-link text-truncate" href = "#">Top on mobile</a>
                </li>
                <li class = "nav-item">
                    <a class = "nav-link" href = "#">Link</a>
                </li>
                <li class = "nav-item">
                    <a class = "nav-link" href = "#">Link</a>
                </li>
                <li class = "nav-item">
                    <a class = "nav-link" href = "#">Link</a>
                </li>
                <li class = "nav-item">
                    <a class = "nav-link" href = "#">Link</a>
                </li>
                <li class = "nav-item">
                    <a class = "nav-link" href = "#">Link</a>
                </li>
                <li class = "nav-item">
                    <a class = "nav-link" href = "#">Link</a>
                </li>
            </ul>
        </div>
        <!-- center content -->
        <div class = "col fluid d-flex flex-column p-0">
            <nav id = "topNav" class = "navbar navbar-expand-md navbar-dark bg-primary">
                <a class = "navbar-brand" href = "#first">Bootstrap 4</a>
                <button class = "navbar-toggler ml-auto py-2" type = "button" data-toggle = "collapse" data-target = "#collapsingNavbar">
                    ☰
                </button>
                <div class = "collapse navbar-collapse" id = "collapsingNavbar">
                    <ul class = "nav navbar-nav">
                        <li class = "nav-item">
                            <a class = "nav-link" href = "#">Link</a>
                        </li>
                        <li class = "nav-item">
                            <a class = "nav-link" href = "#">Link</a>
                        </li>
                        <li class = "nav-item">
                            <a class = "nav-link" href = "#">Link</a>
                        </li>
                    </ul>
                    <ul class = "nav navbar-nav ml-auto">
                        <li class = "nav-item">
                            <a class = "nav-link page-scroll" data-toggle = "modal" title = "A free Bootstrap theme" href = "#aboutModal">About</a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- main content -->
            <div class = "flex-grow">
                <div class = "col-12 py-4">
                    <h3 class = "text-primary hidden-sm-down">Fixed-Fluid-Fixed <span class = "small">(Holy Grail Layout)</span></h3>
                    <h6>Change the width to see the fixed-width side columns.</h6>
                    <p>Wolf moon retro jean shorts chambray sustainable roof party. Shoreditch vegan artisan Helvetica. Tattooed Codeply Echo Park Godard kogi, next level irony ennui twee squid fap selvage. Meggings flannel Brooklyn literally small batch,
                        mumblecore PBR try-hard kale chips. Brooklyn vinyl lumbersexual bicycle rights, viral fap cronut leggings squid chillwave pickled gentrify mustache. 3 wolf moon hashtag church-key Odd Future. Austin messenger bag normcore, Helvetica
                        Williamsburg sartorial tote bag distillery Portland before they sold out gastropub taxidermy Vice.</p>
                    <p>More sustainable roof party. Shoreditch vegan artisan Helvetica. Tattooed Codeply Echo Park Godard kogi, next level irony ennui twee squid fap selvage. Meggings flannel Brooklyn literally small batch,
                        mumblecore PBR try-hard kale chips. Brooklyn vinyl lumbersexual bicycle rights, viral fap cronut leggings squid chillwave pickled gentrify mustache. 3 wolf moon hashtag church-key Odd Future. Austin messenger bag normcore, Helvetica
                        Williamsburg sartorial tote bag distillery Portland before they sold out gastropub taxidermy Vice.</p>
                    <div class = "row">
                        <div class = "col-xl-3 col-md-6">
                            <div class = "card card-block mb-2">
                                <h2 class = "text-center"><span class = "label label-danger">Snippets</span></h2>
                                <h1 class = "text-center">311</h1>
                            </div>
                        </div>
                        <div class = "col-xl-3 col-md-6 mb-2">
                            <div class = "card card-block">
                                <h2 class = "text-center"><span class = "label label-danger">Downloads</span></h2>
                                <h1 class = "text-center">982</h1>
                            </div>
                        </div>
                        <div class = "col-xl-3 col-md-6 mb-2">
                            <div class = "card card-block">
                                <h2 class = "text-center"><span class = "label label-danger">Sales</span></h2>
                                <h1 class = "text-center">112</h1>
                            </div>
                        </div>
                        <div class = "col-xl-3 col-md-6 mb-2">
                            <div class = "card card-block">
                                <h2 class = "text-center"><span class = "label label-danger">Questions</span></h2>
                                <h1 class = "text-center">209</h1>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- /main content -->

            <footer class = "navbar navbar-expand bg-light navbar-light">
                <ul class = "navbar-nav">
                    <li class = "nav-item"><a href = "#" class = "nav-link">Footer</a></li>
                    <li class = "nav-item"><a href = "#" class = "nav-link">Link</a></li>
                    <li class = "nav-item"><a href = "#" class = "nav-link">Link</a></li>
                    <li class = "nav-item"><a href = "#" class = "nav-link">More</a></li>
                </ul>
            </footer>

        </div>

        
    </div>
</div>
<div id = "aboutModal" class = "modal fade" tabindex = "-1" role = "dialog" aria-labelledby = "myModalLabel" aria-hidden = "true">
    <div class = "modal-dialog">
        <div class = "modal-content">
            <div class = "modal-header">
                <h5 class = "modal-title">Modal title</h5>
                <button type = "button" class = "close" data-dismiss = "modal" aria-hidden = "true">×</button>
            </div>
            <div class = "modal-body">
                <p>One fine modal body…</p>
            </div>
            <div class = "modal-footer">
                <button class = "btn" data-dismiss = "modal" aria-hidden = "true">Close</button>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Как я могу сделать этот sidenav на мобильном телефоне слева? Теперь эта боковая панель находится в заголовке. Мне нужна помощь с начальной загрузкой 4. В этом примере я использую container-fluid. На мобильном он есть, но не ушел. Как я могу решить эту проблему? Пожалуйста, помогите решить эту ошибку с бутстрапом 4.

Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Введение в CSS
Введение в CSS
CSS является неотъемлемой частью трех основных составляющих front-end веб-разработки.
Как выровнять Div по центру?
Как выровнять Div по центру?
Чтобы выровнять элемент <div>по горизонтали и вертикали с помощью CSS, можно использовать комбинацию свойств и значений CSS. Вот несколько методов,...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Travel Booking Angular Template один из лучших Travel & Tour booking template in the world. 30+ валидированных HTML5 страниц, которые помогут...
0
0
850
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Это не ошибка Bootstrap 4, и она выглядит как код был скопирован из этого ответа. Посмотрите на столбцы, используемые в разметке, и читать как работает сетка Bootstrap. Левая боковая панель — это col-md-2, поэтому она будет складываться вертикально, как только будет достигнута точка останова md768px.

Как говорится в документах Bootstrap...

"*For grids that are the same from the smallest of devices to the largest, use the .col- classes."

Поэтому, чтобы боковая панель не располагалась вертикально, вы просто измените ее с col-md-2 на col-2.

Кроме того, боковая панель из другой ответ использует nav flex-md-column, из-за чего боковая панель имеет только вертикальное расположение столбцов на md и больше. Принципы те же, что и раньше. Чтобы боковая панель не переключалась на расположение строк при меньшей ширине, измените ее на: nav flex-column.

Демо: https://www.codeply.com/go/wVmmn3AwBb

Спасибо. это работает! Но можем ли мы сделать боковую панель липкой?

Dronax 20.03.2019 13:33

Пожалуйста, проверьте этот код, и он будет работать отлично. Если у тебя есть

Вот код CSS: `

body {
  overflow-x: hidden;
}

#sidebar-wrapper {
  min-height: 100vh;
  margin-left: -15rem;
  -webkit-transition: margin .25s ease-out;
  -moz-transition: margin .25s ease-out;
  -o-transition: margin .25s ease-out;
  transition: margin .25s ease-out;
}

#sidebar-wrapper .sidebar-heading {
  padding: 0.875rem 1.25rem;
  font-size: 1.2rem;
}

#sidebar-wrapper .list-group {
  width: 15rem;
}

#page-content-wrapper {
  min-width: 100vw;
}

#wrapper.toggled #sidebar-wrapper {
  margin-left: 0;
}

@media (min-width: 768px) {
  #sidebar-wrapper {
    margin-left: 0;
  }

  #page-content-wrapper {
    min-width: 0;
    width: 100%;
  }

  #wrapper.toggled #sidebar-wrapper {
    margin-left: -15rem;
  }
}

`

Вот коды HTML: `

<!-- Sidebar -->
<div class = "bg-light border-right" id = "sidebar-wrapper">
  <div class = "sidebar-heading">Start Bootstrap </div>
  <div class = "list-group list-group-flush">
    <a href = "#" class = "list-group-item list-group-item-action bg-light">Dashboard</a>
    <a href = "#" class = "list-group-item list-group-item-action bg-light">Shortcuts</a>
    <a href = "#" class = "list-group-item list-group-item-action bg-light">Overview</a>
    <a href = "#" class = "list-group-item list-group-item-action bg-light">Events</a>
    <a href = "#" class = "list-group-item list-group-item-action bg-light">Profile</a>
    <a href = "#" class = "list-group-item list-group-item-action bg-light">Status</a>
  </div>
</div>
<!-- /#sidebar-wrapper -->

<!-- Page Content -->
<div id = "page-content-wrapper">

  <nav class = "navbar navbar-expand-lg navbar-light bg-light border-bottom">
    <button class = "btn btn-primary" id = "menu-toggle">Toggle Menu</button>

    <button class = "navbar-toggler" type = "button" data-toggle = "collapse" data-target = "#navbarSupportedContent" aria-controls = "navbarSupportedContent" aria-expanded = "false" aria-label = "Toggle navigation">
      <span class = "navbar-toggler-icon"></span>
    </button>

    <div class = "collapse navbar-collapse" id = "navbarSupportedContent">
      <ul class = "navbar-nav ml-auto mt-2 mt-lg-0">
        <li class = "nav-item active">
          <a class = "nav-link" href = "#">Home <span class = "sr-only">(current)</span></a>
        </li>
        <li class = "nav-item">
          <a class = "nav-link" href = "#">Link</a>
        </li>
        <li class = "nav-item dropdown">
          <a class = "nav-link dropdown-toggle" href = "#" id = "navbarDropdown" role = "button" data-toggle = "dropdown" aria-haspopup = "true" aria-expanded = "false">
            Dropdown
          </a>
          <div class = "dropdown-menu dropdown-menu-right" aria-labelledby = "navbarDropdown">
            <a class = "dropdown-item" href = "#">Action</a>
            <a class = "dropdown-item" href = "#">Another action</a>
            <div class = "dropdown-divider"></div>
            <a class = "dropdown-item" href = "#">Something else here</a>
          </div>
        </li>
      </ul>
    </div>
  </nav>

  <div class = "container-fluid">
    <h1 class = "mt-4">Simple Sidebar</h1>
    <p>The starting state of the menu will appear collapsed on smaller screens, and will appear non-collapsed on larger screens. When toggled using the button below, the menu will change.</p>
    <p>Make sure to keep all page content within the <code>#page-content-wrapper</code>. The top navbar is optional, and just for demonstration. Just create an element with the <code>#menu-toggle</code> ID which will toggle the menu when clicked.</p>
  </div>
</div>
<!-- /#page-content-wrapper -->

`

Вот код JQuery:

<script>
    $("#menu-toggle").click(function(e) {
      e.preventDefault();
      $("#wrapper").toggleClass("toggled");
    });
  </script>

Другие вопросы по теме