Reputation: 2007
**CSS**
#child:focus > #parent {
color: white;
}
**HTML**
<div id="parent">
<div id="child">
</div>
</div>
Is this the correct way to apply styles for parent when child is focused ?
Edit: My problem is I need to apply these styles for small devices. So I can't use Jquery. Thats why I am trying within media query in css.
Upvotes: 0
Views: 3490
Reputation: 474
For this particular need was :focus-within
pseudoclass implemented in CSS. In your example following CSS would do what you try to accomplish. I added tabindex
to #child
to make the div
focusable. It is not necessary for elements natively focusable (eg. links or form elements). However, it is not supported by IE and Edge. Edge will support it after planned switch to Blink rendering engine.
See also this CSS Tricks article.
#parent {
padding: 0.25em;
background-color: crimson;
}
#parent:focus-within {
color: white;
}
<div id="parent">
<h1>Parent</h1>
<div id="child" tabindex="0">
<p>Child (click me!)</p>
</div>
</div>
Upvotes: 1
Reputation: 187
CSS have not selector for select up level ... you need solve the your problem use JS
Upvotes: 1
Reputation: 1473
This is possible by 4th Level selecor pseudo-class that works the same as the jQuery implementation.
#parent:has(> #child) { /* styles to apply to the #parent */ }
but this is not currently supported by browsers.
why we don't have a parent selector
Upvotes: 0
Reputation: 1898
You can do this quite simple using JQuery:
$(document).ready(function(){
if ($(window).width() < 960) {
$('.child input').on('focus', function(){
$('.parent').css({
'background-color': 'blue'
});
});
$('.child input').on('blur', function(){
$('.parent').css({
'background-color': 'lightgrey'
});
});
}
});
.parent {
width: 300px;
height: 300px;
display: block;
background: lightgrey;
}
input {
width: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="parent">
<div class="child"><input type="text"></div>
</div>
Upvotes: 0
Reputation: 10782
First, you need to add a tabindex
attribute to your divs, or they can never receive the focus.
I have also included the code to remove the CSS class from the parent when the child loses focus.
$("#child").focusin(function() {
$(this).parent().addClass("focused");
});
$("#child").blur(function() {
$(this).parent().removeClass("focused");
});
.focused {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="parent" tabindex="-1">
Parent Top
<div id="child" tabindex="-1">
Child
</div>
Parent Bottom
</div>
Upvotes: 1
Reputation: 742
You can also use jQuery for this:
$('#child:focus').parent().addClass('your_class');
Upvotes: 1