beatjunky99
beatjunky99

Reputation: 149

percentages and CSS margins

I have create a jsFiddle to demonstrate my problem:

http://jsfiddle.net/MXt8d/1/

.outer {
  display: inline-block;
  vertical-align: top;
  overflow: visible;
  position: relative;
  width: 100%;
  height: 100%;
  background: red;
}

.inner {
  overflow: hidden;
  height: 50%;
  width: 100%;
  margin-top: 25%;
  margin-bottom: 25%;
  background: blue;
  opacity: 0.7;
  color: white;
}

<div class="outer">
    <div class="inner"></div>
</div>

The thing is that when i need to horizontally center a div inside another. I specify the height of the inner div in % (eg. 50%) and then the margin-top and margin-bottom to the remaining (eg. (100 - 50) / 2 = 25 %).

But as you see in the jsFiddle it's not working as intended.

Calculating the margins from the Parent works, but it's not possible for me, because I dont have access to the div's parent, as the elements-style object is bound to the object via knockout.js and it's not so simple as shown in the jsFiddle.

Hope anyone could help me :-)

bj99

Update:

Just found out why this is actually happening, so I'll post here for peaple with similar problems:

From http://www.w3.org/TR/CSS2/box.html#propdef-margin-top :

'margin-top', 'margin-bottom' Percentages: refer to width of containing block

And not as I tought to the height :-/

Upvotes: 0

Views: 304

Answers (3)

Christoph
Christoph

Reputation: 51181

There are various solutions to your problem:

1) add position:absolute and top:25% on the inner element - Example

2) use display:table on the outer and display:table-cell on the inner element, this also allows vertical centering. - Example

Each of the solutions has some caveats, I personally try to avoid absolute positionings wherever I can, but this is also up to personal preferences.

Upvotes: 0

Niki Lichev
Niki Lichev

Reputation: 69

It is a solution to your problem.I hope I helped you

.inner {
  overflow: hidden;
  height: 50%;
  width: 100%;
  top:0;
  bottom:0;
  left:0;
  right:0;
  position: absolute;
  margin: auto;
  background: blue;
  opacity: 0.7;
  color: white;
}

Upvotes: 0

Mihai Matei
Mihai Matei

Reputation: 24276

To #inner element:

1) Add position:absolute

2) Remove margin-top and margin-bottom properties

3) Add top:25%

That's it!

Upvotes: 1

Related Questions