Forum Moderators: not2easy

Message Too Old, No Replies

CSS3 guide: 3.8. only child and only child of a type selectors

         

swa66

10:38 pm on Jun 24, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This is a post in a series, please see the Table of Contents [webmasterworld.com] for the other posts in the series.

3.8. only child and only child of a type selectors

The only child [w3.org] and only child of type [w3.org] pseudo selectors select unique children (of a type).

Syntax: E:only-child

    selects the only child in a parent

Syntax: E:only-of-type

    selects the only child of its type in a parent

Example:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>test</title>
<style type="text/css">
table {
border-collapse: collapse;
text-align: center;
}
td, th {
border: 1px dotted red;
width: 5em;
}
td:only-of-type, th:only-of-type {
color: red;
}
th:only-child {
background-color: yellow;
}
</style>
</head>
<body>
<table>
<tr>
<th colspan="3">wide head</th>
</tr>
<tr>
<th>head</th>
<th>head</th>
<td>cell</td>
</tr>
<tr>
<th>head</th>
<td>cell</td>
<td>cell</td>
</tr>
<tr>
<td colspan="3">wide cell</td>
</tr>
</table>
</body>
</html>

Support:

  • Supported in most standard compliant browsers
  • :only-of-type not supported in Firefox < 3.5
  • Not supported by IE (including IE8)


Graceful fallback:
As always hard to do with selectors

IE8.js adds support for :nth-of-type(1) and :nth-last-of-type(1) which can be combined to simulate :only-of-type; (but with a higher specificity) it also adds :only-child support and as such offers similar or the same functionality in IE7 and IE6.

No known solution for IE8.
No known solution for :only-of-type in Firefox prior to version 3.5

Practical use:
Finding non-essential uses for these selectors isn't all that trivial.

swa66

7:31 pm on Jul 2, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Reserved for future use