skip to Main Content

I am trying to call a class inside another class. But not working. How to do it?

HTML:

   <div class="main">Content</div>
   <div class="cover">Cover content</div>

CSS:

.main{
 width:100%;
 height:360px;
 }
.cover{
 width:90%;
 height:200px;
 }
 .main:focus{ 
    .cover{
    margin-left:12px;
    } 
  }

4

Answers


  1. You have nested your .cover class inside your .main class.

    This means that in your HTML, the nested .cover selector will only apply to elements that are children of elements with a .main class.

    In your code example it will not apply because both your elements are siblings.

    It will work if you write it as:

    <div class="main">
      Content
    
      <div class="cover">
        Cover content
      </div>
    </div>
    

    Note that your Cover Content div element is nested inside your outer Content div element.

    Login or Signup to reply.
  2. in css you can not nest styles, but in sass or less you can.
    in pure css you should write css this way:

     <div class="main">
        <div class="cover">Cover content</div>
        Content
     </div>
    
     .main:focus .cover{
        margin-left:12px;
      }
    
    Login or Signup to reply.
  3. you can’t do this, if you want class cover to be applied on main focus you can use one of these instead:

    if cover is a direct child of main:

    .main:focus>.cover {}
    

    if cover is a sibling of main:

    .main:focus~.cover {}
    

    or

    .main:focus+.cover {}
    
    Login or Signup to reply.
  4. Please pay attention to the answer I give you, so you can learn this topic once and for all. In your HTML, main and cover are adjacent, so you need to use the "+" character to affect them. This means your original code should be sufficient as follows:

    .main:hover + .cover {
                    color: red
            }
    

    In addition, you can also use nesting in pure CSS. Pay attention to the following example:

    .main:hover {
        & + .cover {
                    color: red
            }
    }
    

    Click on the run code snippet below to see the output code

    "Note that I used hover instead of focus to help you better understand and see the output."

    .main {
            width: 100%;
            height: 100px;
        }
    
        .cover {
            width: 90%;
            height: 100px;
        }
    
        .main:hover + .cover {
                        color: red
                }
    <div class="main">Content</div>
        <div class="cover">Cover content</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search