Omer
Omer

Reputation: 163

<div> element isn't at top of it's <div> container

I have a div element (innerBar) inside another one (leftBar), and unless I specify the innerBar's border to have some width, the innerBar isn't starting at the top of the leftBar.

How do fix this?

.leftBar {
  width: 10%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  border: 1px solid red;
}

.innerBar {
  width: 100%;
  height: 100%;
  background-color: lightblue;
  border: 1px solid yellow;
}
<div class="leftBar">
  <div class="innerBar">
    <p>Some Text</p>
  </div>
</div>

Upvotes: 0

Views: 26

Answers (2)

UncaughtTypeError
UncaughtTypeError

Reputation: 8722

It's not necessary to position the nested element out of the document flow at all.

This behaviour is a result of the default margin property declared on the nested p element (specifically the margin-top property), and can be rectified by either one of the following methods:

  1. removing the margin property on the nested p tag:

    .innerBar p {
        margin-top: 0;
    }
    

    * {
      box-sizing: border-box;
    }
    
    .leftBar {
      width: 10%;
      height: 100%;
      position: fixed;
      top: 0;
      left: 0;
      border: 1px solid red;
    }
    
    .innerBar {
      width: 100%;
      height: 100%;
      background-color: lightblue;
      /* additional */
      display: inline-block;
      vertical-align: top;
    }
    <div class="leftBar">
      <div class="innerBar">
        <p>Some Text</p>
      </div>
    </div>

  2. declaring the following additional properties on the nested element (innerBar):

    .innerBar {
        width: 100%;
        height: 100%;
        background-color: lightblue;
        /* border: 1px solid yellow; */
        /* additional */
        display: inline-block;
        vertical-align: top;
    }
    

* {
  box-sizing: border-box;
}

.leftBar {
  width: 10%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  border: 1px solid red;
}

.innerBar {
  width: 100%;
  height: 100%;
  background-color: lightblue;
}

.innerBar p {
  margin: 0px;
}
<div class="leftBar">
  <div class="innerBar">
    <p>Some Text</p>
  </div>
</div>

Upvotes: 1

Omer
Omer

Reputation: 163

Okay got it, I just add to innerBar the property:

position: absolute;

Upvotes: 0

Related Questions