Himanshu Yadav
Himanshu Yadav

Reputation: 13587

Position absolute div width doesn't match parent

I changed child div's position to absolute so that it can fill up rest of the page. But now it's width doesn't match with parent body. Code is not straightforward as I am using Angular 2.

index.html

<body>
  <hp-root></hp-root>
</body>

app.html

<div>
  <md-toolbar class="toolbar">
    <img src="../assets/logo_3x.png" class="top-logo"/>
    <a class="top-link">Home</a>
    <a class="top-link">Candidates</a>
    <a class="top-link">Jobs</a>
    <a class="top-link">Blog</a>
    <a class="top-link">Login</a>
  </md-toolbar>
</div>
<hp-candidate-list></hp-candidate-list>

candidate-list.html

<div class="page">
  <h1>
    {{title}}
  </h1>
  <div class="items">
      <md-nav-list *ngFor="let candidate of candidates">
        <md-list-item>
          <img src="../../../assets/[email protected]" class="reminder">
          <span class="name">{{candidate.name}}</span>
          <span>{{candidate.experiences[0].title}} at {{candidate.experiences[0].companyName}}</span>
          <span>{{candidate.skills[0].name}}, {{candidate.skills[1].name}}, {{candidate.skills[2].name}}</span>
        </md-list-item>
      </md-nav-list>
  </div>
</div>

CSS:

body {
  width: 960px;
  margin: 0 auto;
}

.page {
  overflow: hidden;
  height: 100%;
  position: absolute;
  background-color: gainsboro;
}

div.items {
  max-width: 90%;
  position: relative;
  left: 5%;
  right: 5%;
  background-color: #FFFFFF;
}

After adding the position: absolute .page div fills up rest of the page but looks like this:

enter image description here

Before width was fine but it's height wasn't filling up the page.

Upvotes: 4

Views: 7828

Answers (1)

Stickers
Stickers

Reputation: 78676

Once you set an element to position: absolute, that removes it from the normal content flow, the size of the the element will be the size of the content inside, unless to declare the width and height, or set relevant top, right, bottom and left values.

Example of making an position absolute element to take full width of the closest container with position set other than static, or if it sits directly under body tag.

.page {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
}

or

.page {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
}

EDIT

Example of making div main to fill entire height available by using flexbox.

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  margin: 0;
}
.header {
  background: gold;
}
.main {
  background: silver;
  flex: 1;
}
.footer {
  background: pink;
}
<div class="header">header</div>
<div class="main">main</div>
<div class="footer">footer</div>

Upvotes: 5

Related Questions