判断HTML是否有子节点,css判断某元素的子元素个数,并分别设置样式

工作时遇到这样一个问题:根据某元素所包含的子元素个数,分别设置不同的样式,这个用js可以解决,不过个人认为用css解决可能更简单一点。这也正好加深了我对css选择器的理解和运用。

demo如下:

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

效果图如下

0818b9ca8b590ca3270a3433284dd417.png

完整代码如下:

css3

*{

box-sizing:border-box;

}

ul{

width:100%;

margin:0;

padding:0;

font-size: 0;

}

li{

margin:0;

padding:0;

display:inline-block;

vertical-align: top;

font-size: 13px;

border:1px solid red;

height:30px;

}

/*ul只有一个子元素的样式*/

li:nth-last-child(1):first-child{

width:100%;

}

/*ul有2个子元素的样式*/

/*li:nth-last-child(2):first-child, 是倒数第二个元素,又是第一个元素,说明li的父元素ul有2个子元素(起到了 判断某父元素下有几个子元素 的作用)*/

li:nth-last-child(2):first-child,

/* ~ 选择位于li:nth-last-child(2):first-child 即 第一个子元素之后的元素*/

li:nth-last-child(2):first-child ~ li{

width:calc(100% / 2);

}

/*ul有3个子元素的样式*/

/*第一个元素宽度为1/3,字体颜色为蓝色*/

li:nth-last-child(3):first-child{

width:calc(100% / 3);

color:blue;

}

/*第一个元素之后的第一个元素(即 有3个子元素的ul 的 第 3 个元素)*/

li:nth-last-child(3):first-child ~ li:nth-last-child(1){

width:calc(100% / 4);

color:red;

}

/*第一个元素之后的第一个元素(即 有3个子元素的ul 的 第 2 个元素)*/

li:nth-last-child(3):first-child ~ li:nth-last-child(2){

width:calc(100% / 6);

color:yellow;

}

  • 11111
  • 11111
  • 22222
  • 11111
  • 22222
  • 33333
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 CSS设置一个 `<div>` 元素的坐标位置,以及使另一个 `<div>` 元素的坐标与其相同,你可以使用 `position` 属性和 `top`、`left` 属性来控制元素的位置。 首先,我们需要为父节点设置一个相对定位(`position: relative;`),以便作为参考点给元素定位。 然后,在第一个 `<div>` 元素上,你可以使用绝对定位(`position: absolute;`)来设置其坐标位置。通过设置 `top` 和 `left` 属性来确定元素相对于父节点的位置。 接下来,对于第二个 `<div>` 元素,你可以使用相对定位(`position: relative;`)来保持其在文档流中的位置,并使用 `top` 和 `left` 属性将其移动到与第一个 `<div>` 元素相同的位置。 以下是一个示例代码: HTML 代码: ```html <div class="parent"> <div class="div1"></div> <div class="div2"></div> </div> ``` CSS 代码: ```css .parent { position: relative; } .div1 { position: absolute; top: 50px; left: 50px; width: 100px; height: 100px; background-color: red; } .div2 { position: relative; top: 50px; left: 50px; width: 100px; height: 100px; background-color: blue; } ``` 在上述代码中,我们首先为父节点 `.parent` 设置了相对定位。 然后,我们定义了两个元素 `.div1` 和 `.div2`。`.div1` 使用绝对定位,并通过 `top` 和 `left` 属性设置其坐标位置为 `(50px, 50px)`。`.div2` 使用相对定位,并使用相同的 `top` 和 `left` 属性值 `(50px, 50px)`,使其与 `.div1` 的位置相同。 这样,`.div1` 和 `.div2` 的坐标位置就会相同了。你可以根据实际需要调整它们的样式和位置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值