Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS Show/hide stuff according to checkboxes using CSS

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #249113
    Pranab
    Participant

    Show/hide stuff according to checkboxes using CSS: Why this code won´t work?
    but when i am putting .info after checkbox, then it is working fine..what is the reason for this?
    this is HTML –

    <div class="info">
    <ul>
              <li>first</li>
              <li>second</li>
              <li>third</li>
              <li>fourth</li>
            </ul>
    </div>
    
    <input type="checkbox" class="checkbox"/>
    

    this is CSS –

    .checkbox:checked ~ .info {
      background: #33a2c6;
      box-shadow: 0 0 0 0.2em #000;
      opacity: 1;
      height: auto;
      transition: 0.2s linear;
    }
    .info{
      background: grey;
      margin: 8px;
      opacity: 0;
      transition: opacity 0.2s linear;
    }
    
    #249115
    WayneKenney
    Participant

    Hmmm, I honestly don’t think it’s possible to pull this off with CSS.

    I would use JQuery and do it this way:

    <!-- Include for JQuery -->
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
    
    <!-- Include id 'info' for JQuery reference -->
    <div class="info" id="info">
        <ul>
            <li>first</li>
            <li>second</li>
            <li>third</li>
            <li>fourth</li>
        </ul>
    </div>
    
    <form id="myform">
        <!-- Include id 'checkbox' for JQuery reference -->
        <input type="checkbox" id="checkbox" class="checkbox" checked/>
    </form>
    
    
    <script>
    
    $('#myform :checkbox').change(function() {
    
        // this will contain a reference to the checkbox  
        if (this.checked) {
            // Show info list when checked 
            $("#info").show()
        } else {
            // Hide info list when unchecked
            $("#info").hide();
        }
    });
    </script>
    
    #249116
    Shikkediel
    Participant

    what is the reason for this?

    It is because CSS can only traverse down the document tree. So you can select siblings that follow the element in question but not any that are parsed before it.

    #249120
    Pranab
    Participant

    I would use JQuery and do it this way.

    yeah, with jquery it really simple, but i just wanna explore as much as usage of CSS without using JS / any JS framework and library.

    #249142
    michaelford131
    Participant

    I think you better watch JQUERY :)
    it’s very simple to get the checkbox element and change css.

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘CSS’ is closed to new topics and replies.