Bootstrap Rotating Carets – Pure CSS with Expanding Sections
A really nice feature in Bootstrap is collapsible sections – you can have multiple sections of content that can be displayed or collapsed into a hidden state, which prevents too much clutter in your interface and users feeling like they are staring at an unreadable wall of text. However, how do you signal to your users that they need to click on a target in order to toggle the state of a collapse area? A common preference seems to be carets – E.g. “►” to indicate a collapsed section, and “▼” to indicate that the section is expanded and below the current point.
Bootstrap by default does not include these carets on elements that are triggers for a collapse target, nor does it handle automatically changing their direction depending on the collapse section. However, I came up with a simple pure CSS solution to implement them, which is easily adapted to almost any site. It is not at all complicated and you can find similar guides, but I thought it might still be worth sharing since I also have an example showing how you can combine it with JS to automatically add the carets.
Before any changes: Default setup
Pure CSS solution for auto-rotating carets
You can either add the class “expand_caret” to all your caret elements, or modify my CSS to use “caret” as the target class.
/* PURE css solution for rotating carets based on expanded section */ .expand_caret { transform: scale(1.6); margin-left: 8px; margin-top: -4px; } a[aria-expanded='false'] > .expand_caret { transform: scale(1.6) rotate(-90deg); }
Demo:
Additional solution: Pure CSS for animation, JS to automatically add carets to any collapse triggers.
One of the annoying things about the above solution is that you still have to manually add a placeholder element in the <a></a> that is the toggle for the collapse section. This is best practice, but if you are feeling very lazy, you can use this solution, which uses a bit of JS to automatically add those carets to any link that has
data-toggle=”collapse” as an attribute
Demo: