Focus does not work

856 Views Asked by At

I have the following code: JSBin.

I want the two flex-boxes to initially have grey as background, once we click on one box, its ENTIRE background becomes white. .flex-box .col textarea:focus works as expected, whereas .flex-box .col:focus does not work: the background colour of the text (eg, html, css) is always grey.

Does anyone know what's wrong?

.flex-box {
  display: flex;
  width: 100%;
  margin: 0;
  height: 300px;
}
.flex-box .col {
  border: 1px solid green;
  flex: 1;
  overflow-y: auto;
  overflow-x: hide;
  background: #F7F7F7;
}
.flex-box .col textarea {
  position: relative;
  width: 100%;
  height: 100%;
  resize: none;
  border: 0;
  font-family: monospace;
  background: #F7F7F7;
}
.flex-box .col:focus {
  background: white;
}
.flex-box .col textarea:focus {
  outline: none;
  background: white;
}
<div class="flex-box">
  <div class="col" id="html-panel">
    <h2>html</h2>
    <textarea name="html"></textarea>
  </div>
  <div class="col" id="css-panel">
    <h2>css</h2>
    <textarea name="css"></textarea>
  </div>
</div>

Edit 1:

Actually, once we click on the textarea of a box, I want the background of its title to also become white systematically. It annoys me to set an event listener with JavaScript (because I have already several event listeners). Isn't there a way to realise this with CSS alone?

1

There are 1 best solutions below

3
On BEST ANSWER

This is because the textarea gets :focus not the div. One way to achieve your result with CSS alone is to add an extra div for the background and use the sibling selector when the textarea is focused.

.flex-box {
  display: flex;
  width: 100%;
  margin: 0;
  height: 300px;
}
.flex-box .col {
  border: 1px solid green;
  flex: 1;
  overflow-y: auto;
  overflow-x: hide;
  background: #F7F7F7;
  Position: relative;
}
.flex-box .col textarea {
  position: relative;
  width: 100%;
  height: 100%;
  resize: none;
  border: 0;
  font-family: monospace;
  background: #F7F7F7;
  Z-index: 1;
}
.flex-box .col label {
  display: block;
  font-size: 2em;
  font-weight: bold;
  padding: 10px;
  position: relative;
  Z-index: 1;
}
.flex-box .col:focus {
  background: white;
}
.flex-box .col textarea:focus {
  outline: none;
  background: white;
}
.flex-box .col .background {
  Position: absolute;
  Top: 0;
  Left: 0;
  Right: 0;
  Bottom: 0;
  Height: 100%;
  Width: 100%;
  Z-index: 0;
}
.flex-box .col textarea:focus ~ .background {
  background: white;
}
<div class="flex-box">
  <div class="col" id="html-panel">
    <label for="html">html</label>
    <textarea id="html" name="html"></textarea>
    <div class="background"></div>
  </div>
  <div class="col" id="css-panel">
    <label for="css">css</label>
    <textarea id="css" name="css"></textarea>
    <div class="background"></div>
  </div>
</div>