How to center an element that is wider than its parent element?

时光怂恿深爱的人放手 提交于 2019-12-22 17:53:29

问题


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.


回答1:


.container {
    width:900px
}

iframe {
    margin-left:-25px;
    width:950px;
}



回答2:


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.




回答3:


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




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/5580910/how-to-center-an-element-that-is-wider-than-its-parent-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!