简体   繁体   中英

~ in CSS but for all HTML tags

CSS:

input:focus ~ p {
    color: red;
}

HTML:

<div>
    <input type="text" />
</div>
<p>Please click on the input!</p>

I want to make p red (only with CSS) but input is in div ...

Is it possible? And how?

No you can not traverse up the DOM tree in CSS you would have to use JavaScript, your CSS would work if you markup was just

<input type="text" />
<p>Please click on the input!</p>

Although that would make all siblings and children of siblings P tags after your input red

but if you were using the above markup then it would be safer to use the below CSS which would only select the next sibling:

input:focus + p {
   color: red;
}

If you used jQuery 1.7+ with your original markup you could do:

$( "input" ).on('focus', function() {
  $(this).parent().next().css('color','red');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM