div 的另一个居中问题可以改变大小

Another centering issue with a div that can change size

我试图在 div 中居中对齐 2 个项目。第一个输入框工作正常,因为我可以对宽度进行硬编码。第二个是下拉菜单,它会根据内容更改宽度,因此我无法对宽度进行硬编码。 Text-align 也会使标签居中,display:inline 打破居中,我不想用 JS 进行更改,但我确实意识到这是一个选项。

http://jsfiddle.net/56cgcudb/2/

<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
    <div style="width: 160px; margin: 0 auto; border: solid;">
        <label for="Search" style="">Search</label>
        <input type="text" name="Search" id="Search" placeholder="Search" style="width: 125px" />
        <a class="icon-btn" href="#" style="">
            <i class="icon-magnifier-dark" style=""></i>
        </a>
    </div>
</div>

<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6 " style="">
    <div style=" display: inline-block; margin: 0 auto; border: solid;">
        <label for="dropdownMenu2">Drop Down</label>
        <div class="dropdown" style="">
            <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="">
                option 1
                <span class="caret" style=""></span>
            </button>

            <ul class="dropdown-menu" aria-labelledby="dropdownMenu2" style="">
                <li>
                    <a href="#">Option 1 asdasdasd</a>
                </li>
                <li>
                    <a href="#">Option 2</a>
                </li>
                <li>
                    <a href="#">Option 3</a>
                </li>
                <li>
                    <a href="#">Option 4</a>
                </li>
            </ul>
        </div>
    </div>
</div>

以下是我对水平居中内容所做的操作。创建一个 CSS class:

// Classes
.center-block {
  margin-left: auto;
  margin-right: auto;
  width: 100%; // IMPORTANT: width has to be set to something or centering will not work. You can use ems, but percentages gives you responsive sizing 
}

那么 text-align 呢? 我更喜欢这种方法而不是简单的 text-align,因为这种构造将使 div 中的所有对象居中,而不仅仅是文本。

在您的代码示例中

<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6 center-block">

或者,在任何需要将内容置于 <div>

中心的地方

更新: 居中对齐的内容和左对齐的文本

 // Classes
    .center-block-left-text {
      margin-left: auto;
      margin-right: auto;
      width: 100%; 
      text-align: left !important;
    }

这里有一个很好的官方 CCS reference 关于各种居中。