Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore hidden elements in a Bootstrap Button Group?

I have a button group containing 10 buttons. Under certain screen widths (responsive) I hide some of these buttons with media queries.

The problem is that if I hide the last button the new last button's edges do not become rounded.

It's a difficult problem to describe, but very easy to show in a Fiddle.

My question: how can I add the rounded corners to the last visible button in the button group, rather than simply the last button, as it currently is.

Code from Fiddle below, as per SO's rules:

<div class="btn-group" id="sortBtns" role="group">
    <button type="button" class="btn btn-default">First</button>
    <button type="button" class="btn btn-default">Second</button>
    <button type="button" class="btn btn-default">Third</button>
    <button type="button" class="btn btn-default">Fourth</button>
    <button type="button" class="btn btn-default">Fifth</button>
    <button type="button" class="btn btn-default">Sixth</button>
</div>

<div class="btn-group" id="sortBtns" role="group">
    <button type="button" class="btn btn-default">First</button>
    <button type="button" class="btn btn-default">Second</button>
    <button type="button" class="btn btn-default">Third</button>
    <button type="button" class="btn btn-default">Fourth</button>
    <button type="button" class="btn btn-default">Fifth</button>
    <button type="button" class="btn btn-default" style="display:none;">Sixth</button>
</div>

Note the lack of rounded corners on 'fifth' in the second button group.

I can do this using JavaScript by adding a new class to the last visible element, but I'd rather not. Is there a cleaner CSS-only solution?

like image 408
Mike Avatar asked Jan 28 '15 08:01

Mike


2 Answers

If you don't mind adding a dependency, I recommend AngularJS' ng-if. It comes in handy when using css selectors that rely on an element's position within the DOM, such as the :first-child or :last-child pseudo-classes. It will remove the element from the DOM and allow you to achieve your goal.

like image 63
Edd Avatar answered Oct 22 '22 15:10

Edd


Here's a solution using jQuery:

$('.btn-group').has('.btn:hidden').find('.btn').css('border-radius', 0);
$('.btn-group').has('.btn:hidden').find('.btn:visible:first').css({
    'border-top-left-radius': '3px',
    'border-bottom-left-radius': '3px',
});
$('.btn-group').has('.btn:hidden').find('.btn:visible:last').css({
    'border-top-right-radius': '3px',
    'border-bottom-right-radius': '3px',
});

For each button group with hidden buttons, this will remove the border radii for all buttons within, and then add back border radii for the first and last visible buttons.

OP's Fiddle with solution

like image 42
Marc A Avatar answered Oct 22 '22 16:10

Marc A