skip to Main Content

I want to highlight an element with a border. The problem is that if we add a wrapper (with border) to an element, it shifts the element a bit.
If we run this script on the page we can see it (with dev tools). Script a little glitchy, because I have troubles to detect when mouse leaves the area.

I can’t override parent element properties like (border, outline)
I can’t use {position: relative} on the parent element with pseudo-classes::before/after {position: absolute, content: "", border: ….} (because position value can be different on parent element)

For example we select top questions and the button aligns to the text.before and
after

document.addEventListener('mousemove', e => {
    var element = document.elementFromPoint(e.clientX, e.clientY);
    if (element.id === "_wrapper" || element.parentNode.id === "_wrapper" || element.tagName === "HTML" || element.tagName === "BODY") return;
    var parent = element.parentNode;
    var wrapper = document.createElement("div");
    wrapper.id = "_wrapper";
    
    // set the wrapper as child (instead of the element)
    parent.replaceChild(wrapper, element);
    // set element as child of wrapper
    wrapper.appendChild(element);
}, {passive: true})
 
document.addEventListener("mouseout", e => {
    var element = e.target
    if (element.id === "_wrapper") {
        // remove wrapper
        element.replaceWith(...element.childNodes)
        // element.outerHTML = element.innerHTML;
        // element.replaceChild(element.parentNode, element)
        // console.log(element, element.parentNode)
    }
})

var style = document.createElement('style');
style.innerHTML = `
#_wrapper {
    border: 1px solid;
}
`;
document.head.appendChild(style);

2

Answers


  1. Try this. It will include the "border size" inside the element’s total size so that it will not make any change to element’s previous size.

    #_wrapper {
        border: 1px solid;
        box-sizing: border-box;
    }
    
    Login or Signup to reply.
  2. First of all, on line 1 of the code, you have a typo: "mouseove"

    Second:

    …it shifts the element a bit…

    Use *{box-sizing:border-box}, to prevent borders from changing an element’s width / height.

    Here is a snippet, that I use in all my CSS to prevent things like that (you should too, probably):

    * {
      margin: 0;
      padding: 0;
      border: 0;
      outline: 0;
      list-style: none;
      text-decoration: none;
      box-sizing: border-box;
    }
    
    body {
      overflow-x: hidden;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search