Home > Software design >  Why doesn't the sibling selector work for contenteditable elements?
Why doesn't the sibling selector work for contenteditable elements?

Time:09-30

I've put together this pen: https://codepen.io/NanoSpicer/pen/YzQgQVd

The idea is that using the sibling selector I want to style a certain element when the element before the one I want to style is focused.

It works great with input elements, but it fails miserably when using elements with contenteditable attribute:

.container,
form {
  width: 30%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

div[contenteditable="true"]::before {
  text-color: gray;
  opacity: 0.6;
  content: attr(placeholder);
}

div[contenteditable="true"],
input {
  /* remove system hightlighting*/
  outline-style: none;
  box-shadow: none;
  min-height: 40px;
  appearance: none;
  border: 3px solid;
  border-color: gray;
  border-radius: 6px;
}

div[contenteditable="true"]:focus,
input:focus {
  border-color: blue;
}

*:focus * {
  border-color: red;
}
<form>
  <input placeholder="first" id="first" type="text">
  <input placeholder="second" id="second" type="password">
</form>
<div class="container">
  <div contenteditable="true" placeholder="first"></div>
  <div contenteditable="true" placeholder="second"></div>
</div>

Note: Tested on Firefox and Chrome.

CodePudding user response:

That is very strange. Probably a bug.

This workaround is good for Firefox and Chrome on PC. Didn't test other browsers / platforms.

[contenteditable]:focus   * {
  border-color:green;
}

CodePudding user response:

Just like you did for in the beginning of your CSS, be more specific to indicate you want to react with the contenteditable attribute.

By default, div are not editable, so not focusable, so you have to be a bit more specific with this.

To make this work, you should edit the last CSS property to add the second selector line like I wrote here :

*:focus   *,
div[contenteditable="true"]:focus   div {
  border-color: red;
}

or if you want to make it more generic:

*:focus   *,
*[contenteditable="true"]:focus   * {
  border-color: red;
}
  • Related