Centering a div that overflows with its parent in another centered div

I have one column where the column is a centered div with a fixed width. I want to place a wider div inside a column that overflows with its parents, but centers it inside the parent. Conceptually, something like the following:

<div style="width: 100px; margin: 0 auto; overflow:visible;" id="parent">
    <div style="width: 400px; margin 0 auto;" id="child"></div>
</div>

Centering works as long as the child div becomes thinner than its parent, but as soon as it gets bigger, for some reason it aligns to the left with the parent.

+3
source share
5 answers

I made jsFiddle solution

, , . , , , , , , . div ( ). , , .

FF 3.6, IE7 IE8

+4

Justus. 50% .

#wrapper {
    margin: 0 auto;
    padding: 10px 0 10px;
    width: 200px;
    background-color: #eee;
}
#child {
    margin: 0 -50%;
    width: 400px;
    background-color: #ddd;
}

.

+3

100%, , relative child absolute, top, left width/height div.

0
source

Here is how I solve it:

http://jsfiddle.net/WPuhU/1/

Also take care of the scroll bars (they don't appear if your window view is smaller than the crowded div). Auto centers overflow div.

CSS

#center-3 {height:40px;background-color: #999;}
#center-1 {height:20px;top:10px;background-color: #aaa;}

/* the necesary code */
body {width:100%;margin:0;}
#center-4 {
    width: 100%;
    overflow:hidden;  
    /* remove the next 2 line for a normal flow */
    position: absolute;
    z-index: -1;
}
#center-3 {
    position: relative;
    margin: 0 auto;
    width: 200px;
}
#center-2, #center-1 {
    position: relative;
    width: 400px;
}
#center-2 {
    left: 50%;
}
#center-1 {   
    left: -50%;
}

HTML:

 <div id="center-4">
    <div id="center-3">
        <div id="center-2">
            <div id="center-1"></div>
        </div>
    </div>
</div>
<div id="other-stuff">Here comes the other stuff above.</div>
0
source
#parent {
  position: relative;
  width: 100px;
  overflow: visible;
}

#child {
  width: 400px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}
0
source

Source: https://habr.com/ru/post/1770084/


All Articles