本文操作环境:windows7系统、html5&&css3版、dell g3电脑。
要使用css对html页面中的元素实现一对一,一对多或者多对一的控制,这就需要用到css选择器。html页面中的元素就是通过css选择器进行控制的。
css该如何选择元素呢?
css可以使用:nth-of-type(n)选择器或:last-child选择器来选择元素。:nth-of-type(n)选择器匹配同类型中的第n个同级兄弟元素。:last-child选择器匹配属于其父元素的最后一个子元素的每个元素。
使用:nth-of-type选择器选择元素示例:
<!doctype html><html><head><meta charset="utf-8"> <title></title> <style> p:nth-of-type(2){background:#ff0000;}</style></head><body><h1>this is a heading</h1><p>the first paragraph.</p><p>the second paragraph.</p><p>the third paragraph.</p><p>the fourth paragraph.</p></body></html>
效果图:
使用last-child选择器选择元素示例:
<!doctype html><html><head><style> p:last-child{background:#ff0000;}</style></head><body><h1>这是标题</h1><p>第一个段落。</p><p>第二个段落。</p><p>第三个段落。</p><p>第四个段落。</p><p>第五个段落。</p></body></html>
效果图:
更多详细的html/css知识,请访问css视频教程栏目!
以上就是css如何选择元素的详细内容。
