Oll*_*y F 5 html css css-selectors less
我正在尝试将样式应用到<p>div中的最后一个.我想在不添加新类(或ID)的情况下这样做.
我已经尝试过使用last-child选择器,但它不起作用.
我甚至尝试声明p:last-child {font-style: italic;}我的所有CSS文档,这似乎没有任何影响.
这是我的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>
Run Code Online (Sandbox Code Playgroud)
这是我的LESS 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
看起来这是一个合适的地方:last-of-type,用于选择p其父元素中的最后一个:
.span8 p:last-of-type {
font-style: italic;
}
Run Code Online (Sandbox Code Playgroud)
这是我删除冗余代码后向您展示它是如何工作的一个工作示例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;
}
?
Run Code Online (Sandbox Code Playgroud)
[编辑 - 使用JQuery]
如果你在div.span8中有其他元素并且不知道前面的元素数量,你可以引入一些jquery来实现所需的效果.
这是另一个小提琴: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>
Run Code Online (Sandbox Code Playgroud)
[编辑 - 非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>
Run Code Online (Sandbox Code Playgroud)
所以你必须确保你的<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>
Run Code Online (Sandbox Code Playgroud)