使用 CSS/Jquery 将样式应用于 ul 中的最后一个 li

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/956262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:14:15  来源:igfitidea点击:

Applying Style to last li in a ul with CSS / Jquery

jquerycsscss-selectors

提问by JoshBerke

Given the following HTML:

鉴于以下 HTML:

<ul>
   <li><div>Some content</div></li>
   <li><div>some more content</div></li>
   <li><div>final content</div></li>
</ul>

I would like to apply a top border around each div. On the last div I would like to put a bottom border. I am targeting IE7/8. I have the top border working fine, I need help getting the bottom border.

我想在每个 div 周围应用一个顶部边框。在最后一个 div 上,我想放置一个底部边框。我的目标是 IE7/8。我的顶部边框工作正常,我需要帮助获取底部边框。

I've tried:

我试过了:

   ul > li:last-child > div
    {
        border-bottom: solid 1px black;
    }

I've also tried using last-type-of.

我也试过使用 last-type-of。

I am looking for a CSS solution and a Jquery solution

我正在寻找 CSS 解决方案和 Jquery 解决方案

回答by Paolo Bergantino

Why do you have a <div>inside the <li>? Completely possible without that.

为什么你<div>里面有一个<li>?没有那个完全有可能。

Anyways, this is how to do it with jQuery:

无论如何,这是如何使用 jQuery 做到这一点:

$('ul > li:last-child > div').css('border-bottom','1px solid black');

回答by Lawrence

:last-childis CSS3, unlike :first-childwhich was introduced in CSS2, and has no IE support while. I believe the following is the safest way to implement it using jquery

:last-child是 CSS3,不像:first-child是在 CSS2 中引入的,并且没有 IE 支持。我相信以下是使用 jquery 实现它的最安全的方法

$('li').last().addClass('someClass');

回答by Emily

Here's a CSS only solution:

这是一个仅限 CSS 的解决方案:

Apply the bottom border to the ul. To make it work cross-browser, remove the padding from the ul and bump the list over with a margin.

将底部边框应用于 ul。要使其跨浏览器工作,请从 ul 中删除填充并用边距将列表颠倒。

ul.border {border-bottom:1px solid #000;padding:0;margin-left:40px;}
ul.border li {border-top:1px solid #000;}

<ul class="border">
   <li>Some content</li>
   <li>some more content</li>
   <li>final content</li>
</ul>

回答by ScottE

:last-childdoesn't work in IE7 (not sure on IE8), so you'll have to do the jQuery route. Your css lines up pretty much the same way the selectors would work in jQuery:

:last-child在 IE7 中不起作用(在 IE8 上不确定),因此您必须执行 jQuery 路由。您的 css 排列方式与选择器在 jQuery 中的工作方式几乎相同:

$('ul > li:last > div').addClass('someclass');

回答by leonjorge23

I am not sure why do you need the "<div>" inside the "<li>" but if you don't need it you could simply use:

我不知道为什么你需要“ <div>”里面的“ <li>”,但如果你不需要它,你可以简单地使用:

ul > li:last-child {

I tested it and work for me in chrome, ie8, firefox and safari.

我在 chrome、ie8、firefox 和 safari 中对其进行了测试并为我工作。

回答by Vincent Ramdhanie

$("#yourUL li:last div").css({'border-bottom':'solid 1px black'});