-1

Is it possible to change one class when another is in focus with CSS? For example, .ClassA when .ClassB is in focus

I'm trying to achieve something similar to the apple.com search feature where the menu hides and the search input field expands when selected.

Architect
  • 103
  • 1
  • 2
  • 7

3 Answers3

0

Try this out, it may give you a scent of hope O:-)

However it is very unlikely, that you will get a better solution with pure CSS, it truly is usually made with JavaScript, while each HTML element has list of classes and you may add a class or remove a class quite easily.

<html>
<head>
    <style>
        #spawner {
            display: none;
        }
        #spawner ~ div {
            display: none;
        }
        #spawner:checked ~ div {
            display: block;
        }
    </style>
</head>
<body>
    <label for="spawner">
            <div>Click me to show content!</div>
    </label>

    <input type="checkbox" id="spawner">

    <div>
        Was that a JavaScript? I doubt it!
    </div>
</body>
</html>
Martin Melichar
  • 1,036
  • 2
  • 10
  • 14
0

Maybe something like this?

input { width: 35%; -webkit-transition: width .35s ease-in-out;  transition: width .35s ease-in-out;}
input:focus { width: 100%; }
A. Meshu
  • 4,053
  • 2
  • 20
  • 34
0

const menu = document.querySelector('.menu');
const search = document.querySelector('.search');

search.addEventListener('focus', () => {
  console.log('Focuse');
  search.classList.add('search--active');
  menu.classList.add('menu--hidden');
});

search.addEventListener('blur', () => {
  search.classList.remove('search--active');
  menu.classList.remove('menu--hidden');
});
html, body {
  padding: 0;
  margin: 0;
}

.menu {
  display: flex;
  flex-direction: row;
}

.menu > a {
  padding: 10px;
  color: white;
  text-decoration: none;
  transition: background-color 0.3s;
}

.menu > a:hover {
  background-color: rgba(0,0,0,0.5);
}

.wrapper {
  display: flex;
  flex-direction: row;
  background-color: #eae;
  box-shadow: 0 0 5px #888;
  align-items: center;
  justify-content: space-between;
  padding-right: 10px;
}

.search {
  width: 200px;
  border-radius: 10px;
  transition: width 0.5s;
}

.search--active {
  width: 500px;
  margin-left: auto;
}

.menu--hidden {
  display: none;
}
<div class='wrapper'>

<div class='menu'>
  <a href='#'>Home</a>
  <a href='#'>About</a>
  <a href='#'>Contact Us</a>
  <a href='#'>Support</a>
  <a href='#'>Page</a>
</div>

<input class='search' type='search' name='search' />

</div>
Sergey
  • 7,184
  • 13
  • 42
  • 85