相对于孩子的位置父母[关闭]

问题描述 投票:-3回答:1

我希望让父母使屏幕溢出,从而使div固定在CSS屏幕的左边缘。基本上,我想相对于屏幕定位孩子,但不希望其脱离父母的支持,而是要与孩子一起移动所有父母。

我的目标是使可聚焦的div水平填充屏幕,就像将其放大一样。父元素应使屏幕溢出。基本上我想要这种效果:

Parent
    Child
/Parent
nt
Child
ent

注意父母是如何溢出屏幕的左边缘的。

我的情况是我有一个CSS网格,我想放置整个网格,以使一列位于屏幕的左边缘。

如何使用CSS实现此目标?

html css css-position
1个回答
1
投票

这是使用负的左边距和一些JavaScript的快速概念验证实现。

// 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;
}
<div class="container">
  <div tabindex="0">Item 1</div>
  <div tabindex="0">Item 2</div>
  <div tabindex="0">Item 3</div>
  <div tabindex="0">Item 4</div>
  <div tabindex="0">Item 5</div>
  <div tabindex="0">Item 6</div> 
</div>
© www.soinside.com 2019 - 2024. All rights reserved.