Home > Software engineering >  cannot edit element with `contenteditable` and absolute positioned element
cannot edit element with `contenteditable` and absolute positioned element

Time:02-04

The content element is not editable (not able to select it) despite the z-index being set. How can this hover effect be achieved with the element still being editable?

#outer {
  width: 100px;
  height: 100px;
  position: relative;
  border: 1px solid black;
}

#content {
  z-index: 100;
}

#background {
  z-index: 10;
  position: absolute;
  top: -10px;
  right: -10px;
  bottom: -10px;
  left: -10px;
}

#background:hover {
  background: rgba(90, 90, 90, 0.25);
}
<div id="outer">
  <span id="content" contenteditable>Edit me!</span>
  <span id="background" />
</div>

CodePudding user response:

This would be a more straightforward approach, using only a single element and a pseudo-element. You can use pointer events to make sure the larger background is only visible when you hover the smaller interactive area.

.content {
  position: relative;
  width: 100px;
  height: 100px;
  margin: 10px;
  border: 1px solid;
}
.content:before {
  content: ' ';
  position: absolute;
  display: none;
  inset: -10px;
  background: rgba(90,90,90,0.25);
  z-index: -1;
}
.content:hover:before {
  display: block;
  pointer-events: none;
}
<div  contenteditable>Edit me</div>

CodePudding user response:

This is why your z-index does not work.

z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).

Try this one:

#content {
  position: relative;
  z-index: 100;
}

#outer {
  width: 100px;
  height: 100px;
  position: relative;
  border: 1px solid black;
}

#content {
  position: relative;
  z-index: 100;
}

#background {
  z-index: 10;
  position: absolute;
  top: -10px;
  right: -10px;
  bottom: -10px;
  left: -10px;
}

#background:hover {
  background: rgba(90, 90, 90, 0.25);
}
<div id="outer">
  <span id="content" contenteditable>Edit me!</span>
  <span id="background" />
</div>

  •  Tags:  
  • Related