首页 > 解决方案 > add underline sticky border in the chosen tab

问题描述

HTML

<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'rwaea')">روايات</button>
  <button class="tablinks" onclick="openCity(event, '3am')">ثقافة عامة</button>
</div>

<div id="rwaea" class="tabcontent"></div>

<div id="3am" class="tabcontent">
  <p>Paris is the capital of France.</p> 
</div>

CSS

.tab {
  font-family:sans-serif;
  line-height:24px;
  margin-left:5px;
  overflow: hidden;
  border: 0px;
  background-color: #F0E6E7;
  width:50%;  
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
  border: 0px;
  width:200px;
  border-bottom:2px solid lightgrey;
  font-family: Sans-Serif;
  font-size: 20px;
  line-height:24px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
  border-bottom:2px solid #ca1515 ;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

my code works fine but there's a feature I want to add to my site, but I don't know how. I have two tabs I want to add border to the chosen tab when click on it, I record video to explain what i want to do, please check the video to know what I mean, there's orange border on the chosen tab, I want add this property to my tabs check the video

标签: htmlcssfrontend

解决方案


In order to do what you want, you should use javascript.

const tabs = document.querySelectorAll(".tab");
tabs.forEach(tab => {
  tab.addEventListener('click', function() {
    const current = document.querySelector('.tab.active');
    current.classList.remove('active');
    this.classList.add("active");
  })
})
.flex {
  flex-flow: row nowrap;
  align-items: center;
}

.tab {
  display: inline-block;
  border: none;
  margin: 0 20px;
  border-bottom: 4px solid transparent;
  outline: none;
  cursor: pointer;
}

.tab.active {
  border-bottom-color: orange;
}
<ul class="flex">
  <li class="tab active">Tab 1</button>
  <li class="tab">Tab 2</button>
  <li class="tab">Tab 3</button>
</ul>

Hope it answers your question!


推荐阅读