-4

I am new to CSS and I was just experimenting with it but I came up with a confusion in my code. Below are the two code fragments:

1.

.box h1 {
   font-family: 'Jost', sans-serif;
   text-align: center;
}

2.

h1 .box {
    font-family: 'Jost', sans-serif;
    text-align: center;
}

.box is a class that I have written for my code. Please tell me what difference it is when we write the code 1 & 2.

0stone0
  • 34,288
  • 4
  • 39
  • 64
Ani V.
  • 55
  • 1
  • 9
  • Does this answer your question? [What does a space mean in a CSS selector? i.e. What is the difference between .classA.classB and .classA .classB?](https://stackoverflow.com/questions/1126338/what-does-a-space-mean-in-a-css-selector-i-e-what-is-the-difference-between-c) – 0stone0 May 20 '20 at 10:35
  • the first means: all `h1` inside `.box` get that style applied. numbe 2 means all `.box` in `h1` get this style applied. usually nobody use number 2 – bill.gates May 20 '20 at 10:35

3 Answers3

3

.box h1 are h1 elements inside .box elements

h1 .box are .box elements inside h1 elements

StefanRado
  • 66
  • 3
1

If you put a selector immediately after another, it selects all matching elements of the second selector that are descendants of elements with the first selector.

Example:

<h1>
    <div class="box">
        <div class="box">
        </div>
    </div>
</h1>

All the divs above would be matched by h1 .box. If you flip it around to .box h1, the selector would return all h1s that are descendants of elements with class box, which is none in this case.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
1

In Code 1

.box h1 {
   font-family: 'Jost', sans-serif;
   text-align: center;
}

It is looking for h1 tag inside tag with class .box. and will update the style of that h1 ie.

<div class="box">
    <h1>Some Text</h1>
</div>

Some text here will have style font-family: 'Jost', sans-serif;text-align: center;

In Code 2

h1 .box {
    font-family: 'Jost', sans-serif;
    text-align: center;
}

It is looking for class .box inside h1 tag

ie.

<h1><span class="box">Some</span>Text</h1>

Here styles will be applicable on Some only