Jeremy Smith
Jeremy Smith

Reputation: 15069

How do I make a absolute positioned div have a width equal to it's parent minus some margin

I want to have an inner div that sites inside different sized container divs, and starts at a fixed left position and then has a width that fills up the rest of the container. I've included some example css below to try to get the point across.

I have to use absolute positioning so can't just float right and set a left-margin. Any ideas of how to make this work with absolute positioning? I've also tried width: auto and some different box-sizing options.

To clarify, the trickiness of this is that the left border has to be fixed, and the left border has to be against the right border of the container. I can't use position: relative, and javascript, but I'd probably end up making .inner1 and .inner2 divs with hard-coded widths before doing that. But hoping to avoid that.

.container1 {
  position: relative;
  width: 400px;
  height: 300px;
}

 .container2 {
  position: relative;
  width: 500px;
  height: 300px;
}

.inner {
  position: absolute;
  top: 0px;
  left: 200px;
  height: 100%;
  width: 100%;
}

enter image description here

Upvotes: 40

Views: 56090

Answers (3)

animuson
animuson

Reputation: 54729

Just specify all of the top, left, bottom, and right properties and the box will expand to be at all of those points.

.container {
  position: relative;
  width: 400px;
  height: 300px;
}

.inner {
  position: absolute;
  top: 0;
  left: 200px;
  bottom: 0;
  right: 0;
}

See the jsFiddle.

Upvotes: 80

tkone
tkone

Reputation: 22728

This works. Change the width of the outer box to whatever you want and the inner box grows to match it.

.container {
    width: 400px;
    height: 300px;
} 

.inner {
    position: relative;
    margin-left: 200px;
    height: 100%;
}

Edit: here's a fiddle

Upvotes: -1

haZard0us
haZard0us

Reputation: 41

I don't get what exactly do you need but why don't you use percentages?

Instead of:

.inner {
  position: absolute;
  top: 0px;
  left: 200px;
  height: 100%;
  width: 100%;
}

Why don't you use something like:

.inner {
  position: absolute;
  top: 0px;
  left: 50%;
  height: 100%;
  width: 50%;
}

Setup percentages for left and width attribute accordingly. 40-60, 30-70 and so on.

Hope this helps. If not, please specify a little more.

Regards

Upvotes: 4

Related Questions