1

I have a React component where the container is yellow, but when its input field is expanded it should be orange.

Using only CSS, it possible to change outer-container background color when either: a) input width is expanded, or b) input has focus?

I tried

.outer-container:focus-within {
  background-color: orange;
}

but that does not work because .outer-container:focus-within is still true after clicking 'x' button and it does not go back to yellow. The component is imported and can't access the component's JS, but styled-components package can be used to restyle it. Any ideas?

const {useState} = React;

function Search() {
  const [inputClass, setInputClass] = useState('name');
    return (
    <div className='outer-container'>
      <div className='container'>
        <input className={inputClass} 
          onFocus={() => setInputClass('name-expanded')}
          onBlur={() => setInputClass('name')}
          placeholder="Search" />
        <button className='close'>
          X
        </button>
      </div>
    </div>
  )
}

ReactDOM.render( <Search />, document.getElementById('root') );
.outer-container {
  display: flex;
  position: relative;
  width: max-content;
  background-color: yellow;
  padding: 5px;
}

.outer-container:focus-within {
  background-color: orange;
}

.container {
  display: flex;
  position: relative;
  width: max-content;
  height: 30px;
  align-items: center;
  background: gray;
  border-radius: 16px;
  padding-left: 16px;
  padding-right: 16px;
}

.name {
  min-width: 70px;
  width: 70px;
  outline: none;
}

.name-expanded {
  min-width: 70px;
  width: 150px;
  outline: none;
}

.close {
  position: absolute;
  left: calc(100% - 30px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

<div id="root"></div>
1192805
  • 988
  • 2
  • 10
  • 26

1 Answers1

0

If you want to fix the problem of not turning back to yellow after clicking close button:

.outer-container:has(> .close:selected) {
    background-color: yellow;
}

When the 'X' button is pressed, the div .outer-container would be selected.

c_ptrs
  • 1
  • 2
  • I did not try the code myself, so feel free to give me any feedback! One adding point is that firefox doesn't support :has, as mentioned in https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector – c_ptrs Jan 17 '23 at 03:42