Home > Blockchain >  What does span {} do in CSS syntax?
What does span {} do in CSS syntax?

Time:09-27

I got some example CSS code (well written and working) with many span statements inside, that I modified for my use. What exactly they do? VS Code shows me as an error, but browsers don't complain, and I couldn't find any references in the CSS documentation, as if this syntax does not exist. Example:

h2 {
  letter-spacing: 2vw;
  font-size: 2vw;
  font-weight: bold;
  text-align: center;
  span {
    display: block;
    font-size: 8vw;
    letter-spacing: -1vw;
  }
}

VS code complains:

"code": "css-colonexpected",
"severity": 8,
"message": "colon expected",
"source": "css",

If I add colon it would be suggesting keys right away, and would not accept anything in curly brackets{} Thanks

CodePudding user response:

the brackets { and } define scope so that

   body {
       color: #000;
   }

Would define that the color (text color) of the body element type (css query selector) would be #000 (which is hex for black)

however, if you have an element in an element like this using a precompiler such as less for css using the less syntax.

    body {
        color: #000;
        span {
            color: #FF0000;
        }
    }

this would do as the previous css did, but in less you can create a hierarchy

the body's color will be set to black as before. and then any span child of the body element will have its color set to red (#FF0000)

CSS/LESS are used in conjunction with the HTML DOM object model.

CodePudding user response:

You're correct that this syntax doesn't exist for CSS, as it doesn't support nested selectors like this.

The correct syntax would be:

h2 {
  letter-spacing: 2vw;
  font-size: 2vw;
  font-weight: bold;
  text-align: center;
}

h2 span {
  display: block;
  font-size: 8vw;
  letter-spacing: -1vw;
}

This syntax is of course perfectly acceptable if you use a CSS preprocessor, like SASS or LESS for example. CSS preprocessors compile CSS written like you've done into standard CSS syntax, and add extra functionality, like using variables and conditional statements.

I think that modern browsers are probably capable of understanding syntax like this in certain situations, but if you want to use to this sort of syntax then using a preprocessor is a safer option to avoid errors.

  • Related