float:在水平滚动容器内的元素左侧打破布局

时间:2017-02-24 15:18:02

标签: html css layout

我的容器,带有水平滚动元素,如下所示:

<header id="id-grid-top-menu">

  <div class="cd-dropdown-wrapper">
    <a class="cd-dropdown-trigger">CPB1</a> 
    <nav class="cd-dropdown" style="top: 55px; left: 30px;">
        ...nav code here...
    </nav>
  </div>

  <div class="cd-dropdown-wrapper">
    <a class="cd-dropdown-trigger">CPB1</a> 
    <nav class="cd-dropdown" style="top: 55px; left: 30px;">
        ...nav code here...
    </nav>
  </div>

  <div class="cd-dropdown-wrapper">
    <a class="cd-dropdown-trigger">CPB1</a> 
    <nav class="cd-dropdown" style="top: 55px; left: 30px;">
        ...nav code here...
    </nav>
  </div>
  .......more divs.....
</header>

CSS:

#id-grid-top-menu {
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
    height: 10% !important;
    background-color: white;
    display: block;
}

.cd-dropdown-wrapper {
    float: none;
    height: initial !important;
    position: static !important;
    margin: 15px 15px !important;
    display: inline-block;
}

现在,这看起来像这样:

enter image description here

(抱歉,忽略CPB2)

这个.cd-dropdown-wrapper水平对齐,容器让它溢出overflow-x: scroll。但是,我被迫在float: none元素上设置.cd-dropdown-wrapper。如果我有更少的div,它看起来像这样:

enter image description here

元素都集中在一起。显然,这看起来不太好,我希望元素排在左边。但是,如果我在元素上设置float: left,它们就不再排列并溢出;他们只是四处走动。

enter image description here

.cd-dropdown-wrapper {
    float: left;
}

如何制作它以使它在左侧排成一行,但如果它扩展了屏幕宽度,它仍然会溢出?

修改

我发现了一些有趣的东西。如果,在#id-grid-top-menu中,我设置了固定的宽度 - 比方说,100em。如果我将float: left应用于.cd-dropdown-wrapper,它会在左侧排成一行,然后溢出!但是水平滚动条没有出现......

enter image description here

2 个答案:

答案 0 :(得分:1)

只需在标题标记内添加另一个固定宽度的容器。

<header id="id-grid-top-menu">
  <div id="floatcontainer">
    <div class="cd-dropdown-wrapper">
      <a class="cd-dropdown-trigger">CPB1</a>
      <nav class="cd-dropdown" style="top: 55px; left: 30px;">
        ...nav code here...
      </nav>
    </div>

    <div class="cd-dropdown-wrapper">
      <a class="cd-dropdown-trigger">CPB1</a>
      <nav class="cd-dropdown" style="top: 55px; left: 30px;">
        ...nav code here...
      </nav>
    </div>

    <div class="cd-dropdown-wrapper">
      <a class="cd-dropdown-trigger">CPB1</a>
      <nav class="cd-dropdown" style="top: 55px; left: 30px;">
        ...nav code here...
      </nav>
    </div>
  </div>
</header>

CSS:

#floatcontainer {
   width: 3000px;
}

答案 1 :(得分:0)

添加到@Fabio的代码中,我将float: left放在#floatcontainer上,float: none放在cd-dropdown-wrapper上。这使它发挥作用。