Ray
Ray

Reputation: 349

Collapsible div with css

I'm working on a mobile app. I have the following dummy code. At the moment it is collapsing from bottom to top i.e when I click on the first 3 links, questions gets hidden and you only see the answers.

Is it possible to show both the question and answer when you click on the link. Preferably with just CSS if not javascript.

.faq ul li {
  display:block;
  padding:5px;
  line-height: 8;
}

.faq ul li div {
  display:none;
}

.faq ul li div:target {
  display:block;
}
<div class="faq">
  <ul>
    <li><a href="#question1">Question 1</a>   
      <div id="question1">Answer 1 </div>
    </li>
    <li><a href="#question2">Question 2</a>
      <div id="question2">Answer 2 </div>
    </li>
    <li><a href="#question3">Question 3</a>
      <div id="question3">Answer 3 </div>
    </li>
    <li><a href="#question4">Question 4</a>
      <div id="question4">Answer 4 </div>
    </li>
    <li><a href="#question5">Question 5</a>
      <div id="question5">Answer 5 </div>
    </li>
    <li><a href="#question6">Question 6</a>
      <div id="question6">Answer 6 </div>
    </li>
  </ul>  
</div>

Fiddle: jsfiddle.net/4sKD3/858

Upvotes: 0

Views: 290

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

Instead of using the target this way, make the id and href same for the <a> and use the + adjacent selector to make it work for you.

.faq ul li {
  display: block;
  padding: 5px;
  line-height: 8;
}
.faq ul li div {
  display: none;
}
.faq ul li a:target + a + div {
  display: block;
}
<div class="faq">
  <ul>
    <li>
      <a href="#question1" id="question1">Question 1</a> <a href="#close1" id="close1">Close</a>
      <div>Answer 1</div>
    </li>
    <li>
      <a href="#question2" id="question2">Question 2</a>
      <div>Answer 2</div>
    </li>
    <li>
      <a href="#question3" id="question3">Question 3</a>
      <div>Answer 3</div>
    </li>
    <li>
      <a href="#question4" id="question4">Question 4</a>
      <div>Answer 4</div>
    </li>
    <li><a href="#question5" id="question5">Question 5</a>
      <div>Answer 5</div>
    </li>
    <li>
      <a href="#question6" id="question6">Question 6</a>
      <div>Answer 6</div>
    </li>
  </ul>
</div>

Now having the <a> as the target with the id too, it jumps in the question with the answer displayed next to it. Hope this is what you were expecting. I changed the id to <a> and used the adjacent selector for targetting the <div> this way:

.faq ul li a:target + div

Browser compatibility, every browser in the world! :P

Upvotes: 2

Related Questions