0

I have this code I wrote to recreate a basic site home page:

* {
  box-sizing: content-box;
  margin: 0;
}

body div:first-child {
  background-color: rgba(0, 0, 0, 0.5);
  height: 550px;
  width: 850px;
  margin: auto;
  margin-top: 30px;
  border-radius: 10px;
}

header {
  text-align: center;
}

header :first-child {
  height: 80px;
  margin-top: 50px;
}

header>div {
  background-color: rgb(0, 255, 0);
  height: 30px;
  width: 80%;
  margin: auto;
  display: inline-block;
}
<div>
  <header>
    <img src="" />
    <h2>Taking booleaners from A to B</h2>
    <div>
      <button>Prenota</button>
      <button>Termina Prenotazione</button>
      <button>Accendi Luci</button>
    </div>
  </header>
</div>

The problem is that the buttons get shown below the div despite being its children and I can't understand why this is happening.

enter image description here

biberman
  • 5,606
  • 4
  • 11
  • 35
newbie
  • 15
  • 2
  • 7

1 Answers1

0

This bit

    header :first-child {
        height: 80px;
        margin-top: 50px;
    }

should be

    header > :first-child {
        height: 80px;
        margin-top: 50px;
    }

The current selector applies to all children, and their children. > specifies only the children of the specified parent.

Result: Corrected Result

John Paul R
  • 649
  • 5
  • 10
  • Awesome, remember to mark a question as solved by accepting an answer :) (checkmark at the left) – John Paul R Jun 02 '21 at 22:28
  • @decpk using > works fine while just writing header:first-child is messing up the image idk why – newbie Jun 02 '21 at 22:30
  • BTW, This is not the correct answer. It is just a typo. [:first-child](https://developer.mozilla.org/en-US/docs/Web/CSS/:first-child) – DecPK Jun 02 '21 at 22:30
  • @JohnPaulR yeah imma accept it as soon as the site lets me ahah – newbie Jun 02 '21 at 22:31
  • Then there must be something else that is causing the problem. But this is not how you should proceed. `header > :first-child ` doesn't mean anything at all – DecPK Jun 02 '21 at 22:31
  • @decpk could the image be inheriting its height and width by the div father of header? I didn't write it in the question but it has defined height and width – newbie Jun 02 '21 at 22:33
  • If it somehow works doesn't mean it is the right solution. – DecPK Jun 02 '21 at 22:33
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/233255/discussion-between-decpk-and-newbie). – DecPK Jun 02 '21 at 22:33
  • This is not true. `header > :first-child` is identical to `header > *:first-child`. "If a [universal selector](https://www.w3.org/TR/selectors-3/#universal-selector) represented by * [...] is immediately followed by a pseudo-element, then the * may be omitted and the universal selector's presence implied." – John Paul R Jun 02 '21 at 22:35