Wednesday, 3 October 2018

How Do You Put a Border on Three Sides of an Element?

I saw a little conversation about this the other day and figured it would be fun to look at all the different ways to do it. None of them are particularly tricky, but perhaps you'll favor one over another for clarity of syntax, efficiency, or otherwise.

Let's assume we want a border on the bottom, left, and right (but not top) of an element.

Explicitly declare each side

.three-sides {
  border-bottom: 2px solid black;
  border-right:  2px solid black;
  border-left:   2px solid black;
}

While that's pretty clear, it's still making use of shorthand. Completely expanded it would be like this:

.three-sides {
  border-bottom-color: black;
  border-bottom-style: solid;
  border-bottom-width: 2px;
  
  border-left-color: black;
  border-left-style: solid;
  border-left-width: 2px;
  
  border-right-color: black;
  border-right-style: solid;
  border-right-width: 2px;
}

Knock off one of the sides

You can save a little code by declaring the border on all four sides with shorthand and then removing the one you don't want:

.three-sides {
  border: 2px solid black;
  border-top: 0;
}

Shorthand just the width

.three-sides {
  border-color: black;
  border-style: solid;
  /* top, right, bottom, left - just like margin and padding */
  border-width: 0 2px 2px 2px;
}

As a fun little aside here, you don't need to declare the border color to get a border to show up, because the color will inherit the currentColor! So this would work fine:

.three-sides {
  /* no color declared */
  border-style: solid;
  border-width: 0 2px 2px 2px;
}

And you'd have red borders if you did:

.three-sides {
  color: red;
  border-style: solid;
  border-width: 0 2px 2px 2px;
}

Strange, but true.

If you want to add the color explicity, you can kinda mix-and-match shorthand, so this will work fine:

.three-sides {
  border: solid green; 
  border-width: 2px 0 2px 2px;
}

The post How Do You Put a Border on Three Sides of an Element? appeared first on CSS-Tricks.



from CSS-Tricks https://ift.tt/2y0MDaF
via IFTTT

No comments:

Post a Comment

Passkeys: What the Heck and Why?

These things called  passkeys  sure are making the rounds these days. They were a main attraction at  W3C TPAC 2022 , gained support in  Saf...