DR01D
DR01D

Reputation: 1365

How to absolute position DIV of unknown width

This layout works perfect but only because the last DIVhas a width of 200px. If that DIV had a variable width I couldn't use right:-200px and it wouldn't place correctly.

So my question is what would I do if the DIV with absolute position had a variable width? How would I place it next to the main DIV?

Here is my code.

<div class="outer_container">
<div class="internal_alignment">
    <div class="main_container"></div>
    <div class="column_outside"></div>
</div>              
</div>

CSS

.outer_container {
  overflow: hidden;
  position: relative;
}

.internal_alignment {
  position: relative;
  max-width: 980px;
  margin: 0px auto;
}

.main_container {
  height: 500px;
  background-color: bisque;
}

.column_outside {
  position: absolute;
  top: 0px;
  right: -200px;
  height: 500px;
  width: 200px;
  background-color: black;
}

FYI: the outer_container DIV allows column_outside to sit outside the screen if the browser is smaller than 980px wide.

Upvotes: 0

Views: 139

Answers (3)

Asons
Asons

Reputation: 87262

Make it a child of the main and give it left: 100%;

.outer_container {
  overflow: hidden;
  position: relative;
}
.internal_alignment {
  position: relative;
  max-width: 980px;
  margin: 0px auto;
}
.main_container {
  height: 500px;
  background-color: bisque;
}
.column_outside {
  position: absolute;
  top: 0px;
  left: 100%;
  height: 500px;
  width: 200px;
  background-color: black;
}
<div class="outer_container">
  <div class="internal_alignment">
    <div class="main_container">

       <div class="column_outside"></div>
    </div>
  </div>
</div>


After a second thought, simply use left: 100% instead of right: -200px;

.outer_container {
  overflow: hidden;
  position: relative;
}
.internal_alignment {
  position: relative;
  max-width: 980px;
  margin: 0px auto;
}
.main_container {
  height: 500px;
  background-color: bisque;
}
.column_outside {
  position: absolute;
  top: 0px;
  left: 100%;
  height: 500px;
  width: 200px;
  background-color: black;
}
<div class="outer_container">
  <div class="internal_alignment">
    <div class="main_container"></div>
    <div class="column_outside"></div>
  </div>
</div>

Upvotes: 3

Stickers
Stickers

Reputation: 78736

You can use transform: translateX(100%); what it does is to move the element to the right of the amount of the width of the element itself.

right: 0;
transform: translateX(100%);

Upvotes: 2

Arbel
Arbel

Reputation: 30999

Very simple:

.column_outside {
   right: 0px;
   -webkit-transform: translateX(100%);
   -moz-transform: translateX(100%);
   transform: translateX(100%);
}

Demo https://jsfiddle.net/n4nq6Lxt/

No need to change your HTML structure.

Upvotes: 2

Related Questions