如何用Bootstrap 4 Beta实现Div中Select组件的水平居中?
I can't horizontally center the select component inside a div. Here's my code:
<!--PAGE CONTENT--> <main role="main" class="container-fluid"> <div class="row text-center justify-content-center" style="border: 1px solid red;"> <!--SELECT--> <select id="selectList" style="width: 200px;"> <option></option> <option value="attendance">Närvaro</option> <option value="students">Elever</option> </select> <hr> <!--Js Content--> <div id="jsContent"></div> </div> </main>I've tried multiple Bootstrap classes but none worked. I only found solutions for vertical centering when searching, so I want to focus on horizontal centering here!
Hey there! Let's get that select centered horizontally for you. The core issue here is that <select> elements are inline-block by default, and some of Bootstrap's centering utilities work best with block-level elements. Here are a couple of simple, Bootstrap-native fixes:
Solution 1: Use mx-auto + d-block (Quickest Fix)
Bootstrap's mx-auto utility adds automatic horizontal margins to center elements, but it only works on block-level elements. Since your select is inline-block by default, just add two classes to it:
<select id="selectList" class="d-block mx-auto" style="width: 200px;"> <option></option> <option value="attendance">Närvaro</option> <option value="students">Elever</option> </select>
d-blockconverts the select to a block element, allowingmx-autoto apply the necessary left/right auto margins.- Your fixed width (200px) ensures the element doesn't stretch full-width, so the centering is visible.
Solution 2: Wrap in a Bootstrap Column (Grid-Friendly)
Bootstrap's row class uses flexbox, but it's designed to work with col child elements. Wrapping your select in a col-auto container will play nicely with the row's justify-content-center class, and keeps your markup aligned with Bootstrap's grid system:
<div class="row justify-content-center" style="border: 1px solid red;"> <!--SELECT--> <div class="col-auto"> <select id="selectList" style="width: 200px;"> <option></option> <option value="attendance">Närvaro</option> <option value="students">Elever</option> </select> </div> <hr class="w-100"> <!-- Add w-100 to make the hr span full row width --> <!--Js Content--> <div id="jsContent"></div> </div>
col-autoshrinks to fit the select's width, so the row'sjustify-content-centercenters the column (and the select inside it) perfectly.- Adding
w-100to the<hr>ensures it spans the full width of the row instead of being centered alongside the select.
Either of these solutions should get your select centered horizontally without needing custom CSS beyond what Bootstrap provides!
内容的提问来源于stack exchange,提问作者Björn C

