Explain Codes LogoExplain Codes Logo

Border length smaller than div width?

html
css
responsive-design
box-shadow
Alex KataevbyAlex Kataev·Oct 3, 2024
TLDR

To create a "compressed border", utilize a ::before pseudo-element featuring position: absolute; nested within a position: relative; parent div. The pseudo-element's width should match the desired border length you wish to achieve, while its height determines the thickness of the 'border.'

.div-with-small-border::before { content: ''; position: absolute; // Our "border's" coordinates are relative to the parent div. bottom: 0; // Our "border" is chilling at rock bottom.. left: 50%; // half-way across its world (our div). transform: translateX(-50%); // It spotted a bug in the middle, so it's tweaking its location slightly. width: 100px; /* How long do you want your "border-ladder" */ height: 2px; /* Skinny or thick border? Choose its diet plan. */ background: black; /* Border color or the dress of our "border-hero" */ z-index: 1; // Our "border" wants to be the first. }

Applying this CSS to a suitably styled div gives the appearance of a bottom border of diminished length. Adapt the width value to adjust length, and height to determine thickness.

Customizing your border buddy

  • To center-align the border, set the left property and use transform: translateX(-50%);.
  • Play with the z-index, so our border shows up just where you want it to.
  • Use max-width not to limit our border's creativity, but rather to ensure it behaves well with different screen sizes.
  • The box-shadow can also join the party, offering a neat alternative trick to pull off with similar effects, and some pretty "radial" style too.

Shadows say, "We can mimic borders too!"

Ever considered box-shadow for a custom length border? Try this:

.div-with-shadow-border::before { content: ''; position: absolute; bottom: 0; left: 0; box-shadow: inset 0px -2px 0px 0px black; /* Trying to play shadow puppetry */ width: 100%; /* Ensure the shadow fills up the stage */ height: 100%; /* Again for our div-theatre */ }

The box-shadow property paves the way for creative border styles. A negative spread value helps form a sharp ending, hinting a border cut-off. Shadows do light up lives after all.

More ways to border while breaking boundaries

  • Linear gradient technique: Create distinguishing border styles with background gradients for a fancy flair.
  • Additional div structure: Need an alternative no matter what? An additional div just to act as the border can fill in too.