显示侧边栏时,导航栏中有两种背景颜色

Have two background colors in the navbar when the sidebar is shown

我制作了一个简单的页面,其中有 navbarbootstrap 和一个边栏:JSBin。目前,导航栏的背景色为 black.

现在,我想完成以下工作:

1) 当页面宽度不足以显示侧边栏时,我希望导航栏的背景颜色完全是 black.

2) 然而,当页面足够宽以显示侧边栏时,我希望侧边栏 上方的导航栏区域 具有不同的背景颜色(例如,white).就像下面的截图,侧边栏上方的区域是 blue,而导航栏的其余部分是 white.

我尝试使用 <div class="col-sm-3 col-md-3"> 在导航栏中添加一个元素,但没有成功。好像这个只能包含在container或者container-fluid.

有人知道如何实现吗?有什么解决方法吗?

1) when the page is NOT wide enough to show the sidebar, I want the background color of the navbar to be entirely black.

您可以将媒体查询添加到您的 body 标签中,只需将其包含在 css

中的 body 之后
 @media (max-width: 768px) {
    body {
      background-color: #000; // black color for background
    }
  }

2) Whereas, when the page is wide enough to show the sidebar, I want the area of the navbar above the sidebar to have a different background color (eg, white). Like the following screenshot, the area above the sidebar is blue, while the rest of the navbar is white.

您可以将项目名称移到导航栏之外并应用它的宽度和颜色。

不要忘记添加媒体查询以使导航栏保持白色 :)

 @media (min-width: 768px) {
    .sidebar {
      position: fixed;
      top: 51px;
      bottom: 0;
      left: 0;
      z-index: 1000;
      display: block;
      padding: 20px;
      overflow-x: hidden;
      overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
      background-color: #f5f5f5;
      border-right: 1px solid #eee;
    }
    .navbar-inverse {
      background-color: #F8F8F8; // background color of navbar
      border-color: #E7E7E7; // border color of navbar
    }
  }

您需要的部分

<div class="col-sm-3 col-md-3" style="background-color: #428bca; border-color: #E7E7E7;">
  <a class="navbar-brand" href="#">Project name</a>
</div>

完整的导航栏

<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="col-sm-3 col-md-3" style="background-color: #428bca; border-color: #E7E7E7;">
    <a class="navbar-brand" href="#">Project name</a>
  </div>
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <div id="navbar" class="navbar-collapse collapse">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Dashboard</a></li>
        <li><a href="#">Settings</a></li>
        <li><a href="#">Profile</a></li>
        <li><a href="#">Help</a></li>
      </ul>
      <form class="navbar-form navbar-right">
        <input type="text" class="form-control" placeholder="Search...">
      </form>
    </div>
  </div>
</nav>

这里是JSBin