Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hover on one element changes on another with css only

Tags:

css

Hi its a very basic question i just want to know when hover on one element the style of other changes how can I achieve this ?

<form id="numerical" class="row">
  <div class="form-group row">
    <label>Enter Number :</label>
    <input type="text" id="tel">
  </div>
  <div class="form-group row">
    <label>Result :</label>
    <input type="text" id="result">
  </div>
  <button type="submit" id="btn" class="row">Submit</button>
</form>

Like when i hover on button border-color of all the input changes. I only want this with css no js or jQuery.

like image 892
Saiyam Gambhir Avatar asked Aug 29 '26 02:08

Saiyam Gambhir


2 Answers

It is possible to do this but not with your current code.

Below is code of this working, the hover element will have to be before the elements you want to change. It works by going down and not up, so if this button is at the bottom you will not be able to see the same effect as the effect does not effect elements that are already rendered.

button:hover ~ div input {
  border: 1px solid red;
}
<form id="numerical" class="row">
  <button type="submit" id="btn" class="row">Submit</button>
  <div class="form-group row">
    <label>Enter Number :</label>
    <input type="text" id="tel">
  </div>
  <div class="form-group row">
    <label>Result :</label>
    <input type="text" id="result">
  </div>
</form>

We can select other elements siblings by using the ~ selector.

The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.

More here


Here is the button at the bottom, as you can see it will not work.

button:hover ~ div input {
  border: 1px solid red;
}
<form id="numerical" class="row">
  <div class="form-group row">
    <label>Enter Number :</label>
    <input type="text" id="tel">
  </div>
  <div class="form-group row">
    <label>Result :</label>
    <input type="text" id="result">
  </div>
  <button type="submit" id="btn" class="row">Submit</button>
</form>
like image 132
Ruddy Avatar answered Aug 30 '26 18:08

Ruddy


for a pure css solution you need to move the <button>-tag in front of the inputs you want to change, but then it'll work like this

button:hover ~ .form-group input {
    border-color: red;
}
<form id="numerical" class="row">
    <button type="submit" id="btn" class="row">Submit</button>
    <div class="form-group row">
    <label>Enter Number :</label>
    <input type="text" id="tel">
  </div>
  <div class="form-group row">
    <label>Result :</label>
    <input type="text" id="result">
  </div>
</form>
like image 31
Alex Avatar answered Aug 30 '26 18:08

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!