如果:target不存在,如何为元素设置默认样式 [英] How to set a default styling to element if :target doesn't exist

查看:65
本文介绍了如果:target不存在,如何为元素设置默认样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含3个链接的标头,所有链接都链接到具有相应ID的特定div:

I have a header with 3 links, all linking to a specific div with a corresponding id:

body {
  font-size: 32px;
}

.links {
  display: flex;
  a {
    padding: 10px;
  }
}

.box:not(:target) {
  display: none;
}

#box1 {
  background-color: crimson;
}

#box2 {
  background-color: darkgreen;
}

#box3 {
  background-color: gold;
}

<div class="links">
  <a href="#box1">Box1</a>
  <a href="#box2">Box2</a>
  <a href="#box3">Box3</a>
</div>

<div class="box" id="box1">Box1 content</div>
<div class="box" id="box2">Box2 content</div>
<div class="box" id="box3">Box3 content</div>

我想使用CSS伪类在定位时将所选元素从display:none转换为display:block.我是使用.box:not(:target) { display:none }实现的.

I want to use the CSS pseudo class to turn the selected element from display:none to display:block when targetted. I achieved this using .box:not(:target) { display:none }.

问题在于,如果只有css的三个框中不存在:target,我想默认将框显示为第一个框(#box1),将不胜感激! >

The problem is that I would like to default the boxes to show the first box (#box1) if :target does not exist amongst the three boxes with css only if possible, any help would be greatly appreciated!

推荐答案

请按照以下代码段操作,希望您的问题可以通过html和css来解决,

Follow below the snippet, hope your problem will fix with html and css,

body {
  font-size: 32px;
}

.links {
  display: flex;
  a {
    padding: 10px;
  }
}

.box:not(:target) {
  display: none;
}
#box1{
  display: block;
}
#box2:target ~ #box1,
#box3:target ~ #box1{
  display: none;
}




#box1 {
  background-color: crimson;
  
}

#box2 {
  background-color: darkgreen;
}

#box3 {
  background-color: gold;
}

<div class="links">
  <a href="#box1">Box1</a>
  <a href="#box2">Box2</a>
  <a href="#box3">Box3</a>
</div>


<div class="box" id="box2">Box2 content</div>
<div class="box" id="box3">Box3 content</div>

<div class="box" id="box1">Box1 content</div>

box1是默认设置,当您触发box2,box3时,您可以看到box1将不显示任何内容. 主要是用于通用同级选择器(〜)"

the box1 is default and when you trigger the box2, box3 you can see box1 will get display none. mainly it's working for "general sibling selector (~)"

这篇关于如果:target不存在,如何为元素设置默认样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆