Home > Blockchain >  Linking directly to a CSS tab
Linking directly to a CSS tab

Time:12-21

I'm trying to figure out how to give somebody a direct link to a CSS tab on my page, but giving them pagename.html#tab2 doesn't work. If it's possible to do this without a script, it would be best, but I'm open to anything at this point. BTW, feel free to tear apart my code! I'm just learning how to do this, so it may not be as efficient as it should be! Thanks!

/* Tabs */

input  /*hide radio buttons */
{
  display: none;
}

input label  /* show labels in line */
{
  display: inline-block;
  font-size: 1.3em;
}

input~.tab  /* show contents only for selected tab */
{
  display: none;
}

#tab1:checked~.tab.content1,
#tab2:checked~.tab.content2 {
  display: block;
}

input label {
  border: 1px solid #999;
  background: #101010;
  padding: 4px 12px;
  border-radius: 6px 6px 0 0;
  position: relative;
  top: 1px;
}

input label:hover {
  background: #212121;
}

input:checked label {
  background: transparent;
  border-bottom: 2px solid #292929;
}

input~.tab {
  border-top: 1px solid #999;
  padding: 12px;
}
<div style="background-color: #292929;color: #b2b2b2;line-height: 1.5em;font-family: Mulish,sans-serif;">
  <input type="radio" name="tabs" id="tab1" checked="checked" />
  <label for="tab1">Tab 1</label>
  <input type="radio" name="tabs" id="tab2" />
  <label for="tab2">Tab 2</label>
  <div >
    <p>Tab content 1</p>
  </div>
  <div >
    <p>Tab content 2</p>
  </div>
</div>

CodePudding user response:

If you specify

<input type="radio" name="tabs" id="tab1" checked />

then this radio button will be checked by default when the page is loaded. If you want the other tab to be checked you can do that by getting the hash from the URL and then checking it programmatically like so

<script>
// this will be #tag2 in your case
let hash = document.location.hash;

// remove the hash sign
hash = hash.slice(1, hash.length);

let tab = document.getElementById( hash );

// check the required input element
tab.setAttribute('checked', 'checked');

</script>

You will want to include this script near the end of your body, well after the input elements are loaded.

CodePudding user response:

use

scrollIntoView()

check this doc on it: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

I hope this helps

  • Related