我正在尝试将样式应用于div中的最后一个<p>
。我想这样做而不添加新的类(或ID)。
我尝试使用最后一个选择器,但是它不起作用。
我什至尝试为所有CSS文档声明p:last-child {font-style: italic;}
,但这似乎没有任何效果。
这是我的HTML:
<div class="new-section">
<div class="collection-container">
<div class="container">
<div class="row">
<div class="title span16">
<h1>The Title</h1>
</div>
<div class="span8">
<p>Some text.</p>
<p>This collection includes video, audio and essays.</p>
<p>Visit now</p>
<div class="arrow-right"></div>
</div>
</div>
</div>
</div>
</div>
这是我的更少CSS:
.collection-container {
height: 200px;
position: relative;
background-color: @gray;
.container {
padding-top: @r-margin;
.title {
margin-bottom: @xs-margin;
}
.span8 p:last-child {
font-style: italic;
}
}
}
最佳答案
这是删除多余代码以向您展示其工作方式后的工作示例http://jsfiddle.net/RDpcM/1/
始终是,这是格式化代码并尝试分解调试时重要部分的一个好主意。很容易弄错一个右括号,并且一切都变成了梨形。
<div class="span8">
<p>Some text.</p>
<p>This collection includes video, audio and essays.</p>
<p>Visit now</p>
</div>
div p:last-child {
font-style: italic;
border:solid 1px blue;
}
[编辑-使用JQuery]
如果div.span8中还有其他元素并且不知道元素的数量,则可以引入一些jquery来实现所需的效果。
这是另一个 fiddle :http://jsfiddle.net/VPbv2/
否则这将作为一个独立的示例供您试用。加载文档时,JQuery动态设置
mySelected
类。<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<style type="text/css">
.mySelected {
font-style: italic;
border:solid 1px blue;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("div.span8 > p:last").addClass("mySelected");
});
</script>
</head>
<body>
<div class="span8">
<p>Some text.</p>
<p>This collection includes video, audio and essays.</p>
<p>Visit now</p>
<div>xxx</div>
</div>
</body>
</html>
[编辑-非JQuery]
您指出,拥有此代码后,原始答案将不起作用
<div class="span8">
<p>Some text.</p>
<p>This collection includes video, audio and essays.</p>
<p>Visit now</p>
<div> another non-P tag that will mess up the p:last-child selector</div>
</div>
因此,必须将
<p>
标记包装在这样的额外div中,以确保没有其他兄弟标记<div class="span8">
<div class="only-for-p">
<p>Some text.</p>
<p>This collection includes video, audio and essays.</p>
<p>Visit now</p>
</div>
<div> this non-P tag no longer messes with the p:last-child selector</div>
</div>