为什么要设置css max-width,但div仍会扩展?

时间:2019-07-02 03:58:54

标签: css bootstrap-4

我正在使用引导程序4,当内容文本长度过长(不能用省略号表示)时,在移动视图上导航.nav .dropdown-menu和.text-truncate时遇到问题。

我尝试将max-width 100%设置为.dropdown-menu,这样子元素只能将最大宽度扩展为父级宽度。

screenshot actualy happen

此处是代码

<nav class="navbar navbar-expand-sm navbar-dark bg-dark shadow fixed-top">
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapse-husr-navbar" aria-expanded="true">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="navbar-collapse collapse show" id="collapse-husr-navbar" style="">
      <ul class="navbar-nav" id="navbar-husr-right">
        <div class="d-block d-sm-flex">
          <div class="p-2 text-truncate">
            <span class="d-inline">
              <i class="fas fa-map-marker-alt"></i>
              <small><span id="husr-branch-name">DUMMY BRANCH A</span></small>
            </span>
          </div>
        </div>
        <li class="nav-item dropdown show">
          <a class="nav-link dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="true">
            <span class="d-inline d-sm-none d-md-inline d-lg-inline">Menu</span>
          </a>
<!-- here the first I try to put max-width:100%; so children element can't push parent to expand, but not work. :( -->
          <div class="dropdown-menu dropdown-menu-right show" style="max-width:100%">
            <span class="dropdown-item-text text-nowrap" style="
">
              <i class="fas fa-user"></i>
              <span id="husr-user-name">Staff User</span>
              (<em><span id="husr-user-type">STAFF</span></em>)
            </span>

<!-- here the second I try to put max-width:100%; so children element can't push parent to expand, but also not work. :( -->
            <span class="dropdown-item-text head-email"  style="max-width:100%">
<!-- here the third time put max-width:100%; so children element can't push parent to expand, butthis also not work. :( -->
              <div class="text-truncate" style="max-width:100%">
                <i class="fas fa-envelope"></i>
                <span id="husr-user-username">i_mean_it_to_be_ellipsis_text_truncated_but_container_div_still_expanded</span>
<!-- yeah the text has no space because it contain an email that should be nospace -->
              </div>
            </span>
          </div>
        </li>
      </ul>
    </div>
  </nav>

screenshot expected

1 个答案:

答案 0 :(得分:1)

要使text-overflow工作,您需要一个最大宽度,但也需要overflow: hidden。您应该可以删除text-truncate div并使用以下CSS:

.head-email {
    max-width: 100%;
    white-space: nowrap;
    overflow: hidden;
}

来自MDN documentation for text-overflow

  

text-overflow属性不会强制发生溢出。要使文本溢出其容器,您必须设置其他CSS属性:overflowwhite-space

编辑:
在您的情况下,576像素以下的引导程序不会限制导航栏本身的大小。在您的div上添加类max-width: 100%;的{​​{1}}可以修复较小的视口。