1 reply [Last post]
goldxdust22
goldxdust22's picture
Offline
newbie
Last seen: 3 years 21 weeks ago
Timezone: GMT-4
Joined: 2016-05-22
Posts: 1
Points: 2

What is the difference between this element-specific selector:
h2.artist {

and this descendant selector?:

.artist h2 {

Are they the same? If so, when would you use one over the other?

Thanks!

gary.turner
gary.turner's picture
Offline
Moderator
Dallas
Last seen: 18 hours 42 min ago
Dallas
Timezone: GMT-5
Joined: 2004-06-25
Posts: 9743
Points: 3822

Differences are subtle, but important

The first example sz if the h2 element is of class 'artist', {do this}. Only elements that are of the class and the element's descendants are affected. (Headings never have descendants other than phrase elements.)

The second example applies only to the class's descendant h2.

For example,

<!DOCTYPE HTML>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta content=
	    "width=device-width, height=device-height, initial-scale=1"
            name="viewport">
    <title>
      Test document
    </title>
    <style type="text/css">
    /*<![CDATA[*/
 
    body {
	background-color: white;
	color: black;
	font: 100%/1.5 sans-serif;
	margin: 0;
	padding: 0;}
 
    p {
	font-size: 1em;}
 
    h1,
    h2 {
	font-family: serif;
	margin-bottom: 0;}
 
    #page {
	margin: 0 auto;
	padding-top: 1px;
	width: 90%;}
 
    .index {
	color: red;}    
 
    /*]]>*/ 
    </style>
  </head>
  <body>
    <div id="page">
      <h1 class="index">
        GTWebDev
        <br>
        <small>Where the accessible, usable web site is king</small>
      </h1>
    </div>
    <!-- end page -->
  </body>
</html>

Now add this ruleset:
    .index small {
	color: green;
	font-family: sans-serif;
	font-style: italic;}

cheers,

gary

If your web page is as clever as you can make it, it's probably too clever for you to debug or maintain.