// adjusts the container's margin to align the focused item
const focusHandler = ({target}) => {
// get the left position of the focused element.
const {left} = target.getBoundingClientRect();
// get the left position of the container.
const {left: containerLeft} = container.getBoundingClientRect();
// adjust the container's left margin
container.style.marginLeft = `${containerLeft - left}px`;
}
// listen for all focusin events on the container
const container = document.querySelector('.container');
container.addEventListener('focusin', focusHandler);
.container {
font-family: sans-serif;
display: flex;
width: 100vw; /* prevent the container from getting wider as the margin changes */
}
.container div {
flex: 1 1 auto;
background: #eee;
padding: 16px;
margin: 8px;
}
.container :focus {
background: bisque;
color: tomato;
}