4

I have below HTML and I want to hide all divs having class 'msg' excluding one div having same class.

<html>

<div class="ref" >
    <div class="msg">  Message ref </div>
</div>

<div class="msg">  Message 1 </div>
<div class="msg">  Message 2 </div>
<div class="msg">  Message 3 </div>

</html>

Here I want to hide all div having class 'msg' except div which is inside another div having class 'ref' using css only.

My style for that is

.msg:not(.ref.msg) {
     display: none;
}

But it is not working.Please suggest me some required tweaks to my CSS style to achieve result.

Thanks.

5
  • 2
    .ref .msg add a space between both the classes, your code states that div with the class of ref & msg together. hence insert a space between .ref .msg Commented Sep 14, 2015 at 9:23
  • I suspect this is not possible as there is no parent selector which I think is required here as :not only accepts simple selectors. Commented Sep 14, 2015 at 9:23
  • @WisdmLabs still not working after adding space between classes Commented Sep 14, 2015 at 9:25
  • @Paulie_D Suggest the way round Commented Sep 14, 2015 at 9:27
  • There is no single selector that can do this...see the answers below. Commented Sep 14, 2015 at 9:34

3 Answers 3

6

You can try this

<style>
    .msg{
     display: none;
    }
    .ref .msg{
     display: block;
    }

</style>

Edit Note: If you want to apply the 'not'rule I think you would need this structure

<style>
    div:not(.ref){display: none;}
</style>
<div class="msg ref">  Message ref </div>
<div class="msg">  Message 1 </div>
<div class="msg">  Message 2 </div>
<div class="msg">  Message 3 </div>`
Sign up to request clarification or add additional context in comments.

2 Comments

No doubt,It's working But Could we do it in single styling?
I think that having you're structure if code is quiet difficult to do it in a single styling rule, note that you have you're "ref" class div inside another div what means that you're working in differents levels. You will need the code that I add on the edit note to apply the 'not' rule
2

Try the below code:

CSS

.ref :not(.msg) {
    display: none;
}

Html

<div class="ref" >
    <div class="msg">  Message ref 1 </div>
</div>
<div class="ref" >
    <div class="msg1">  Message ref 2 </div>
</div>
<div class="msg">  Message 1 </div>
<div class="msg">  Message 2 </div>
<div class="msg">  Message 3 </div>

make sure you add a space after .ref class.

Comments

1
.msg { display:none; }

.ref .msg { display:block; }

This should be working.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.