I am trying to center align 2 items inside divs. The first input box works fine since I can hard code the width. The second, being a drop down, will change its width based on the content so I can't hard code a width. Text-align will center the label also, display:inline breaks the centering and I prefer not to have to do changes with JS, but I do realize that's an option.
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>
Here's what I do for horizontally centering content. Create a 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
}
So what about text-align? I prefer this method over a simple text-align, because this construct will center all objects in the div, not just text.
And in your code example
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6 center-block">
Or, wherever you need to center stuff in a <div>
Updated: Center aligned content and left-aligned text
// Classes
.center-block-left-text {
margin-left: auto;
margin-right: auto;
width: 100%;
text-align: left !important;
}
Here's a good official CCS reference about centering of all sorts.