Wednesday, March 29, 2023

pure CSS recreating a focus box (that doesn't touch the content)

Sigh. One of those times when maybe if my googling mojo had been better I could have saved myself some time. Here's the codepen I made to learn about the following...

We are messing around with divs including some that might be able to have focus, and I got to wondering what options were for making a focus box, or something similar for hover.

One option is to make a border:
.card.border:hover {
  border:  8px solid blue;
}

the trouble is that might mess up your alignment, cause some shifting, unless it has a border in its non-active mode as well, ala
.card.border {
  border:  8px solid blue;
}

But that might distort things anyway. So it might be safer to use a boxshadow, possibly making sure the fuzz ratio is 0 (or not, if you want a less harsh look)

.card.boxshadow:hover {
 box-shadow: 0 0 0 8px red;
}

 But what if you don't a frame, rather than a border per se? Like one that isn't touching the content, yet doesn't require changes to the content in the layout, or risk moving things around?

I came up with this to give a nice such frame on hover:

.card.before {
  position:relative;
}
.card.before:hover::before {
  border:  4px solid red;
  content:"";
  position: absolute;
  top:-20%;
  bottom:-20%;
  left:-20%;
  right:-20%;
}

Position:relative was a little awkard...

But there is of course a simpler solution - I had missed the simple "outline" property, which when combined with "outline-offset" gave me just the look I was thinking of:

.card.outline:hover{
  outline: 4px solid blue;
  outline-offset:8px;
}

(outline-offset supported in most things but IE)



No comments:

Post a Comment