Gurshaan Singh
Gurshaan Singh

Reputation: 1

How to position divs using Relative and Absolute positioning

I want my display to look like this.

Expected Layout

But instead, it looks like this

Actual Layout

My Code goes like this.

HTML

 <body>
  <div class="top">
    <div class="left">
      <h1>TOP LEFT</h1>
    </div>
    <div class="right">
      <h1>TOP RIGHT</h1>
    </div>
  </div>
  <div class="bottom">
    <h1>BOTTOM</h1>
  </div>
</body>

CSS

body{
  text-align:center
}

.top{
  position:relative;
}

.left{
  position:absolute;
  width:50%;
}

.right{
  position:absolute;
  width:50%;
  left:50%;
}

.bottom{
  position:relative;
}

What necessary changes should I make in my code. I want to keep things dynamic and not specify the height of divs in pixels.

Upvotes: 0

Views: 42

Answers (1)

Quentin
Quentin

Reputation: 943142

Don't. Positioning is unsuited to this type of layout.

Use the right tool for the job. Use flexbox to put the two elements side-by-side, and let normal flow handle the rest.

h1 {
  text-align: center;
}

.top {
  display: flex;
}

.top>div {
  flex: 0 0 50%;
}
<div class="top">
  <div class="left">
    <h1>TOP LEFT</h1>
  </div>
  <div class="right">
    <h1>TOP RIGHT</h1>
  </div>
</div>
<div class="bottom">
  <h1>BOTTOM</h1>
</div>

Upvotes: 4

Related Questions