Manuel Keddensky
Manuel Keddensky

Reputation: 53

Is it possible to focus the div and change Css from another ?

div:focus ~ .div2 {
    background-color:red;
    height:400px;
    margin-top:20px;
    margin-left:20px;
};

If the user click on the div the CSS from div2 should change. It that possible with this code ?

Upvotes: 3

Views: 7241

Answers (2)

G-Cyrillus
G-Cyrillus

Reputation: 106048

the tabindex attribute is needed to make div catch the focus. use value:0 , so it doesn't mess up with the order of other element which can have the focus via tab .

https://html.spec.whatwg.org/multipage/interaction.html#attr-tabindex

An element with the tabindex attribute specified is interactive content.

https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex

0 means that the element should be focusable and reachable via sequential keyboard navigation, but its relative order is defined by the platform convention;

div {border:solid;
}

div:focus~.div2 {
  background-color: red;
  height: 400px;
  margin-top: 20px;
  margin-left: 20px;
}
.div2 {
  background-color: yellow;
  height: 200px;
  margin-top: 0px;
  margin-left: 0px;
  transition: 0.5s;
}
<div tabindex="0"> click or tab can give me the focus, click outside and i loose it </div>
<div class="div2"> div2</div>

Upvotes: 5

Michael Coker
Michael Coker

Reputation: 53709

The :focus pseudo class is for form elements. You can use a form element instead, or use a different pseudo class, like :hover

Here is an input with :focus

input:focus ~ .div2 {
    background-color:red;
    height:400px;
    margin-top:20px;
    margin-left:20px;
}
<input type="text">
<div class="div2">bar</div>

And here is your div with :hover

div:hover ~ .div2 {
    background-color:red;
    height:400px;
    margin-top:20px;
    margin-left:20px;
}
<div>foo</div>
<div class="div2">bar</div>

You can fake the :focus thing with regular text by using a checkbox hack. (or radio hack, in your case, to emulate :focus by making the changes to .div2 when you click on the text)

input:checked ~ .div2 {
    background-color:red;
    height:400px;
    margin-top:20px;
    margin-left:20px;
}
input {
  display: none;
}
<input type="radio" id="foo"><label for="foo">foo</label>
<div class="div2">bar</div>

Upvotes: 0

Related Questions