Vijay
Vijay

Reputation: 117

Display div initially when page is loaded

I need to toggle between student and staff div using two link buttons in a html page(i.e only one div should be displayed in the page and other will be hidden when the button is clicked).

The problem is the code works only when the button is clicked and when the page initially loads no div is displayed and the page is blank. I want to display student div by default when page loads and then toggle between student and staff div based on the button clicked.

How to achieve this using HTML and CSS?

.panel {
    overflow-y: auto;
    overflow-x: hidden;
    margin-top: -150%;
    position: absolute;
    background: #000;
    color: #fff;
    box-shadow: 0px 4px 7px rgba(0,0,0,0.6);
    z-index: 2;
}
.panel:target {
    position: relative;         
    margin-top: 0%;
    background-color: black;
}
<a href="#student">Students</a>
<a href="#staff">Staffs</a>
<div id="student" class="panel">
student content
</div>
<div id="staff" class="panel">
staff content
</div>

Upvotes: 1

Views: 65

Answers (1)

gilly3
gilly3

Reputation: 91557

Your default panel should appear last in the HTML. Create a rule to show that last panel by default. Create a rule to hide that last panel, when it is the sibling of the target panel.

.panel, .panel:target ~ #student {
    overflow-y: auto;
    overflow-x: hidden;
    margin-top: -150%;
    position: absolute;
    background: #000;
    color: #fff;
    box-shadow: 0px 4px 7px rgba(0,0,0,0.6);
    z-index: 2;
}
.panel:target, #student {
    position: relative;         
    margin-top: 0%;
    background-color: black;
}
<a href="#student">Students</a>
<a href="#staff">Staffs</a>
<div id="staff" class="panel">
staff content
</div>
<div id="student" class="panel">
student content
</div>

Credit to this answer for the idea.


By the way, why are you using position: absolute and margin: 150% to hide the panels instead of the very simple display: none?

Upvotes: 1

Related Questions