Button Group Template
Group together related actions into a single, cohesive unit with this flexible button group component.
This is a classic UI pattern used for creating toolbars, view switchers, or any set of options that should be visually connected.
About the Button Group
A button group visually merges multiple buttons, removing the space between them to imply a strong relationship. It's an effective way to organize an interface and reduce clutter. To be accessible, a button group should be contained within an element that has a role="group" and an aria-label that describes the purpose of the group as a whole.
Features
- Cohesive Design: CSS is used to collapse the margins and merge the borders between adjacent buttons, making them appear as a single element.
- Accessible Grouping: The containing
divusesrole="group"and anaria-labelto properly inform screen readers what the group of controls is for. - Flexible Content: The buttons can contain just text, just icons, or a combination of both.
- CSS-Only and Easy to Use: The styling logic is handled entirely by CSS, making the component simple to implement.
Code Breakdown
The structure is a parent div with role="group" and multiple button elements inside. The main styling comes from a few CSS rules. First, Flexbox is used on the container to align the buttons. Then, to create the joined effect, CSS targets every button that is not the first one (.btn-group-1 > :not(:first-child)) and removes its left-side border-radius and sets its margin-left to a negative value that equals the border width. A similar rule removes the right-side border-radius of every button that is not the last one.
Code
Here is the complete code for the accessible button group.