Downhillski
Downhillski

Reputation: 2655

how to position two boxes to make them align well?

I want to put the both h1 and inner box to the upper left corner of the outer box.

Here is my attempt, but failed. I am looking for a javascript free solution.

.outer {
  position: absolute;
  margin: 50px;
  width: 300px;
  height: 300px;
  background-color: blue;
}
h1 {
  position: relative;
  top: 0;
  left: 0;
}
.inner {
  position: relative;
  width: 100px;
  height: 100px;
  top: 0px;
  left: 0px;
  background-color: red;
}
<div class="outer">
  <h1>
some text
</h1>
  <div class="inner">
  </div>
</div>

Upvotes: 1

Views: 56

Answers (3)

Rapha&#235;l VO
Rapha&#235;l VO

Reputation: 2640

You are using wrong the position:absolute. In your case, to make your code work, change from position:absolute to position:relative in .outer.

When you tell an element to use postion:absolute, it will bring that element out of the DOM, and it will looking for the nearest parent which has position:relative.

Note: I don't know why you are using position in this example, because this is the last option I will take if I need to align these elements, you can play around with display:inline-block or display:flex to make your elements align correctly!

Upvotes: 1

GSaunders
GSaunders

Reputation: 548

You'll want to use relative positioning for the outer box, and absolute for the inner box. For the h1, make sure it's inside the inner box and then you can use padding instead of explicit widths and heights.

https://jsfiddle.net/hnezfs3k/1/

<div class="outer">
  <div class="inner">
    <h1>
      some text
    </h1>
  </div>
</div>



.outer {
  position: relative;
  width: 400px;
  height: 400px;
  background-color: blue;
}
h1 {
  color: #fff;
}
.inner {
  padding: 8px;
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(255, 0, 0, .5);
}

Upvotes: 1

Tim
Tim

Reputation: 5691

Use absolute instead of relative positioning.

.outer {
  position: absolute;
  width: 300px;
  height: 300px;
  background-color: blue;
  margin: 20px;
}
h1 {
  position: absolute;
  top: 0;
  left: 0;
}
.inner {
  position: absolute;
  width: 100px;
  height: 100px;
  top: 0px;
  left: 0px;
  background-color: rgba(255, 0, 0, .5);
}
<div class="outer">
  <h1>
some text
</h1>
  <div class="inner">
  </div>
</div>

Upvotes: 2

Related Questions