How to align bootstrap 4, horizontal list group in

2019-08-26 07:06发布

问题:

I'm using this snippet of code from here (shown below) to horizontally align items in a list group (in Bootstrap 4).

    .list-group.list-group-horizontal{
        display: flex;
        flex-direction: row;
    }

    .list-group.list-group-horizontal .list-group-item {
        margin-bottom: 0;
        margin-right: 0;
        border-right-width: 0;
    }
    .list-group.list-group-horizontal .list-group-item:first-child {
        border-top-right-radius:0;
        border-bottom-left-radius:4px;
    }
    .list-group.list-group-horizontal .list-group-item:last-child {
        border-top-right-radius:4px;
        border-bottom-left-radius:0;
        border-right-width: 1px;
    }

How can I center align the list group? I tried adding class text-center and some other things, however I did not succeed.

<div id="app" class="container my-container">

    <!-- Header -->
    <h2 class="text-center" >Sample Header</h2>

    <!-- Buttons -->
    <div class="list-group list-group-horizontal">
        <a href="#" class="list-group-item active">Categories</a>
        <a href="#" class="list-group-item">Search</a>
    </div>

</div>

Codepen

回答1:

For posterity: Apply d-flex justify-content-center if your element is not a flex element.

Original Answer: Apply justify-content-center to the list-group

Codepen: https://codepen.io/anon/pen/gZRzOR

Here it is in the documentation: https://getbootstrap.com/docs/4.0/utilities/flex/#justify-content

<div class="list-group list-group-horizontal justify-content-center">
....
....
</div>


回答2:

Use Justify content, to change the horizontal placement of your elements:

.list-group.list-group-horizontal {
    display: flex;
    flex-direction: row;
}

.list-group.list-group-horizontal .list-group-item {
    margin-bottom: 0;
    margin-right: 0;
    border-right-width: 0;
}

.list-group.list-group-horizontal .list-group-item:first-child {
    border-top-right-radius:0;
    border-bottom-left-radius:4px;
}

.list-group.list-group-horizontal .list-group-item:last-child {
    border-top-right-radius:4px;
    border-bottom-left-radius:0;
    border-right-width: 1px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div id="app" class="container">

    <!-- Header -->
    <h2 class="text-center" >Sample Header</h2>

    <!-- Buttons -->
    <div class="list-group list-group-horizontal d-flex justify-content-center">
        <a href="#" class="list-group-item active">Categories</a>
        <a href="#" class="list-group-item">Search</a>
    </div>
</div>