Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS :focus-within selector for an element with an iframe child

I have a scenario like this:

.container {
  background: yellow;
  padding: 40px;
}

.container:focus-within {
  background: red;
}

iframe {
  background: white;
}
<div class="container">
  <input type="text" placeholder="Input 1">
  <iframe srcdoc="<input type='text' placeholder='Input 2'>"></iframe>
</div>

As you can see, when I click on input 1 to type, the container turns red because of the :focus-within selector. But when I focus input 2 (inside the iframe), it doesn't.

Is it possible to use a CSS selector on .container for if something inside the iframe is focused? I have control over the CSS inside the iframe as well.

like image 293
Ethan Avatar asked Sep 23 '18 05:09

Ethan


People also ask

How do I focus in SCSS?

:focus is a pseudo-class used to select and style elements, usually links and form elements, that have been focused by the user, either by "tabbing" using the keyboard or by clicking. Form elements, such as <input> , <button> , and <textarea> can receive focus either by tabbing using the keyboard or by clicking.

How do you add focus in CSS?

The :focus CSS pseudo-class represents an element (such as a form input) that has received focus. It is generally triggered when the user clicks or taps on an element or selects it with the keyboard's Tab key.

What CSS selector should we use if we want to select all elements but not the specified class or selector?

For selecting everything but a certain element (or elements). We can use the :not() CSS pseudo class.

Is () CSS pseudo class?

The :is() CSS pseudo-class function takes a selector list as its argument, and selects any element that can be selected by one of the selectors in that list. This is useful for writing large selectors in a more compact form.


1 Answers

not by css but with jQuery, you can add class to container when input 2 focused, and remove class when it loses focus.

<style>
 .container:focus-within, .container.in_iframe {
            background: red;
        }
</style>

<script>
    $('document').ready(function () {
        $('#iframe').on('load', function () {
            var iframe = $('#iframe').contents();
            iframe.find("input").on('focus', function () {
                $('.container').addClass('in_iframe');
            });
            iframe.find("input").on('focusout', function () {
                $('.container').removeClass('in_iframe');
            });
        });
    });
</script>

full code: https://codepen.io/peker-ercan/pen/PdgEOy

like image 75
Ercan Peker Avatar answered Sep 17 '22 08:09

Ercan Peker