将下拉按钮的宽度设置为与下拉项目的宽度相同

时间:2019-06-01 17:48:15

标签: html css twitter-bootstrap bootstrap-4

我有一个下拉div,其按钮宽度与其下拉项目的宽度不同。我希望按钮和下拉菜单的宽度相同。

<div class="dropdown col">
    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose a form</button>
    <ul class="dropdown-menu col-xs-12">
        <a class="dropdown-item" href="#">word</a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="#">word</a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="#">Very long word</a>
    </ul>
</div>

Very long word项目的宽度与word项目的宽度相同,只是按钮的宽度不同。

2 个答案:

答案 0 :(得分:1)

我不确定您是否从标签中寻找引导程序的特定答案,但是一种选择是将.dropown的父容器display: flex设置为flex-direction:column ,在flex父主轴上扩展子项。

.dropdown {
  display: flex;
  flex-direction: column;
}

答案 1 :(得分:1)

一种方法是将按钮和下拉菜单包装到新的div并在其中设置所需的宽度(我为示例设置了200px的宽度),然后仅使其子元素(按钮+下拉菜单)继承父级的div宽度(width: inherit !important;),如下所示:

<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">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>


<div class="dropdown col">
    <div style="width: 200px;">
        <button style="width: inherit !important;" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose a form</button>
        <ul style="width: inherit !important;" class="dropdown-menu dropdown-menu-center">
            <a class="dropdown-item" href="#">word</a>
            <div class="dropdown-divider"></div>
            <a class="dropdown-item" href="#">word</a>
            <div class="dropdown-divider"></div>
            <a class="dropdown-item" href="#">Very long word</a>
        </ul>
    </div>
</div>