1

I am dynamically displaying either 3 or 4 divs that need to be centered within a container div. How do I ensure that the divs are always centered given their static bootstrap column values?

<div>    
    <div class="col-md-3">foo</div>
    <div class="col-md-3" ng-show="settings.isShown">bar</div>
    <div class="col-md-3">foo</div>
    <div class="col-md-3">bar</div>
</div>
jgillich
  • 71,459
  • 6
  • 57
  • 85
MarkusJ
  • 87
  • 2
  • 8
  • Obviously the stupid approach is to use JS to update the classes of the divs to be 4 columns wide when displaying 3 divs, thereby maintaining the total column width of 12. – MarkusJ Jun 26 '14 at 22:33
  • 1
    if you are dynamically adding the columns, can you not dynamically decide if you should use col-md-3 or col-md-4? – blurfus Jun 26 '14 at 22:37
  • Sorry, I should have been more clear. The fact that there is either 4 or 3 divs is dynamic. All the divs are rendered on the page. The 2nd div is either shown or hidden based on a javascript variable. – MarkusJ Jun 26 '14 at 22:43

1 Answers1

1

it looks like you're pairing this with AngularJS

in which case you can apply a ternary operator on ng-class to your <div>s so that they dynamically change class based upon the state of settings.isShown:

<div>    
    <div ng-class="(settings.isShown) ? 'col-md-3' : 'col-md-4'">foo</div>
    <div class="col-md-3" ng-show="settings.isShown">bar</div>
    <div ng-class="(settings.isShown) ? 'col-md-3' : 'col-md-4'">foo</div>
    <div ng-class="(settings.isShown) ? 'col-md-3' : 'col-md-4'">bar</div>
</div>

This solution assumes you are on Angular 1.1.5 or higher (they only added ternary operator support since then)

For other options on applying conditional classes to elements with AngularJS see https://stackoverflow.com/a/12151555/648350

Community
  • 1
  • 1
haxxxton
  • 6,422
  • 3
  • 27
  • 57
  • Your answer is clever because it leverages Angular to change the classes with little code. Ideally, I would like to keep the widths of the divs the same but still centered within the containing div. I will accept this as my only possible option (and the answer) if nothing better is suggested. – MarkusJ Jun 26 '14 at 22:54
  • so when you say "still centered". 3 x `col-md-3` inside a `container` class in bootstrap will have them pulled to the left? do you have other css that is changing this default behaviour? – haxxxton Jun 26 '14 at 23:05
  • No other css. Correct, they do pull to the left. – MarkusJ Jun 26 '14 at 23:10
  • so when you say 'still centered' what did you mean? do you mean that you want to use the columns at the width they are now and center them before the toggle-able column appears? – haxxxton Jun 26 '14 at 23:38
  • Correct. Only 3 divs showing, centered in the container without having to increase the width of the divs. – MarkusJ Jun 27 '14 at 01:32