2

I currently have a div with a fixed width of 900px.
I'd like to add a child iframe with a fixed width of 950px, and I'd like it to be perfectly aligned to the center.
How can that be done?

Thanks.

Lior
  • 5,454
  • 8
  • 30
  • 38

5 Answers5

6

You can place the child at 50%, then use a negative margin that is half the width of the child:

.parent { position: relative; overflow: hidden; }
.child { position: absolute; left: 50%; top: 0; margin-left: -475px; }

This way you only need to know the size of the child element.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
3

I found a way to do it with dynamical widths here: http://www.greywyvern.com/?post=323

Gregory Bolkenstijn
  • 10,003
  • 7
  • 36
  • 38
  • Very awesome technique, but you should definitely put the relevant parts here in the answer in case the remote site ever goes down. Ping me when you do and I'll upvote you. – Mike Jun 28 '16 at 23:37
2

Another way would be to use:

   .parent {
     position:relative;
   }
   .child {
     position:absolute;
     left:50%;
     transform:translateX(-50%);
   }

which works even if you do not know the size of child nor parent, but will not work in older browsers.

qbolec
  • 5,374
  • 2
  • 35
  • 44
1
.container {
    width:900px
}

iframe {
    margin-left:-25px;
    width:950px;
}
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
1

I assume your outer container width is 950px and child iframe width is 900px then you can use margin:0px auto; for your child container in css