Explain Codes LogoExplain Codes Logo

Css Inset Borders

html
responsive-design
css
performance
Anton ShumikhinbyAnton Shumikhin·Sep 15, 2024
TLDR

To create an inset border using CSS, use the box-shadow property:

.inset-border { box-shadow: inset 0 0 0 2px #000; /* quick border */ }

Apply this to an element for a sharp, inset border effect:

<div class="inset-border">Content</div>

Include multiple box-shadow instances for creating layered effects. Need different transparent levels? Use the respective RGBA values.

.multi-layer-border { box-shadow: inset 0 0 0 2px rgba(0, 0, 0, 0.5), inset 0 0 0 4px #fff; /* sandwiched border */ }

Pseudo-elements and Inset Borders

Border Designs with Pseudo-elements

Using the ::before or ::after pseudo-elements, we can create complex border designs on the HTML element:

.inset-border::before { content: ''; position: absolute; top: -2px; right: -2px; bottom: -2px; left: -2px; box-shadow: inset 0 0 0 2px #000; pointer-events: none; /* don't play hide and seek with clicks */ }

Just remember to have your parent element positioned relatively.

Controlling Outlines and CPU Performance

Crafting slim or controllable widths is possible with a combination of outline and outline-offset. And, let's be CPU-friendly: excessive shadows could turn your sleek UI into a snail's pace tortoise race. 🐢💨

Be Border Smart: Customize and Differentiate

Size Does Matter: Control Your Border Spread

With box-shadow, you can customize its fourth pixel value to control spread. A slight adjustment can lead to either broad or tight enclosures, potentially adding a je ne sais quoi touch to your design.

Align Your Borders to Devised Layouts

The box-sizing: border-box rule makes sure your borders fit neatly within the element's box, maintaining harmony with functional layout paradigms.

Interactivity without Interference

When stylizing interactive elements, pointer-events: none on pseudo-elements ensures that they don't steal the thunder from click or touch events.