【CSS属性选择器灵活应用】以选择父元素下第一个不隐藏的class为“item“的div为例

1 篇文章 0 订阅

欢迎来到我的博客

原始需求

大div下多个子div,子项会根据后端给的数据来做显示和隐藏(用display来控制),子项的边框为border:1px solid #ccc,只有第一项display不为none的项需要border-left,其余的项都需要设置border-left: none
html代码结构:

// 大概这样子
<!DOCTYPE html>
<html>
<head>
<style>
html,body {
  width: 100%;
  height: 100%;
}
.wrap {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.wrap .item {
  border: 1px solid #ccc;
  width: 108px;
  height: 58px;
  line-height: 58px;
  display: flex;
  justify-content: center;
  align-items: center;
}


</style>
</head>
<body>
<div class="wrap">
    <!-- 样式display:none;是由vue中v-show来控制 不固定在某条 -->
	<div class="item" style="display:none;">数据一</div>
    <div class="item">数据二</div> 
    <div class="item">数据三</div>
    <div class="item">数据四</div>
    <div class="item"  style="display:none;">数据五</div>
    <div class="item">数据六</div>
    <div class="item">数据七</div>
    <div class="item">数据八</div>
</div>
</body>
</html>

效果图如下:
效果图

解决方案

<!DOCTYPE html>
<html>
<head>
<style>
html,body {
  width: 100%;
  height: 100%;
}
.wrap {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.wrap .item {
  border: 1px solid #ccc;
  width: 108px;
  height: 58px;
  line-height: 58px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.item:not(:nth-of-type(1)) {
	border-left: none;
}

.item[style*='display:none;'] + div[class*='item'] {
	border-left: 1px solid #ccc;
}

div[class*='item'] + .item[style*='display:none;'] + div[class*='item'] {
	border-left: none;
}


</style>
</head>
<body>
<div class="wrap">
    <!-- 样式display:none;是由vue中v-show来控制 不固定在某条 -->
	<div class="item" style="display:none;">数据一</div>
    <div class="item">数据二</div> 
    <div class="item">数据三</div>
    <div class="item">数据四</div>
    <div class="item" style="display:none;">数据五</div>
    <div class="item">数据六</div>
    <div class="item">数据七</div>
    <div class="item">数据八</div>
</div>
</body>
</html>

修改记录:

  1. .item:not(:nth-of-type(1)) { border-left: none; },表示将父节点.wrap下的不在第一项所有子项.itemborder-left设置为none
  2. .item[style*='display:none;'] + div[class*='item'] { border-left: 1px solid #ccc; },表示将紧挨着displaynone的一项(.wrap下第一个不为none的)设置左边框border-left
  3. div[class*='item'] + .item[style*='display:none;'] + div[class*='item'] { border-left: none; },表示将中间任意一项或多项.item设置为隐藏display: none的项的border去除。

效果图如下:
效果图

结束语

第一次写博客,记录下,哦豁豁~~

资料链接🔗
[1]: https://www.w3school.com.cn/cssref/css_selectors.asp
[2]: https://developer.mozilla.org/zh-CN/docs/Web/CSS/:nth-of-type

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值