CSS on: focus within child contenteditable

I am trying to detect focusin a child of an element contenteditablefor the purpose of stylish CSS styling. (I know I can detect this with JS, add an extra class and do it this way, but it takes so long.)

Basically, I have something like:

<div contenteditable="true">
  Some text <span class="edit">that</span> goes here.
</div>

I tried CSS line by line:

.edit:focus {
  color: #FF0000;
}

I want the spancolor to change when the carriage enters it, but apparently the focus only applies to divthat set to contenteditable, and not to any child element. I tried applying the second contenteditableto span, but besides being a terribly sloppy approach, it still doesn't work.

Is there a solution for this?

+4
4

- , contenteditable , , <span>, , ( Firefox selectionchange).

var selectionContainer = null;

function updateSelectionContainer() {
  var newSelectionContainer = null;
  var sel;
  if (window.getSelection && (sel = window.getSelection()).rangeCount) {
    newSelectionContainer = sel.getRangeAt(0).commonAncestorContainer;

    // Ensure we have an element rather than a text node
    if (newSelectionContainer.nodeType != 1) {
      newSelectionContainer = newSelectionContainer.parentNode;
    }
  }
  if (newSelectionContainer != selectionContainer) {
    if (selectionContainer) {
      selectionContainer.className = selectionContainer.className.replace(/ ?containsSelection/, "");
    }
    if (newSelectionContainer) {
      newSelectionContainer.className +=
        (newSelectionContainer.className ? " containsSelection" : "containsSelection");
    }
    selectionContainer = newSelectionContainer;
  }
}

if ("onselectionchange" in document) {
  document.onselectionchange = updateSelectionContainer;
} else {
  var el = document.getElementById("editor");
  el.onmousedown = el.onmouseup = el.onkeydown = el.onkeyup = el.oninput = updateSelectionContainer;
  window.setInterval(updateSelectionContainer, 100);
}
div {
  font-size: 200%;
}

.edit.containsSelection {
  color: red;
  font-weight: bold;
}
<div contenteditable="true" id="editor">
  Some text <span class="edit">that</span> goes here.
</div>
Hide result
+1

, , (), .

. SO

- tabindex .

body {
  font-size: 3rem;
}
div[contenteditable=true] .edit:focus {
  color: #FF0000;
}
<div contenteditable="true">Some text <span class="edit" tabindex="0">that</span> goes here.</div>
Hide result
+2
:focus > .edit { color: #cc0000; }

<div contenteditable="true">Some text <span class="edit">that</span> goes here.</div>
<div contenteditable="true">Some text that goes here.</div>
+2

: focus. Fiddle.

.edit {
  color: #f00;
}
0

All Articles