当前位置: 动力学知识库 > 问答 > 编程问答 >

html - Center a div with dynamic width in a parent where the width can be bigger than the parent

问题描述:

Okay I hope I can make clear what I need.

I have 5 Divs: a wrapper, div 1, div 2, div 3 and div 4.

HTML:

<div id="main">

<div id="one">1</div>

<div id="two">2

<div id="four">4</div>

</div>

<div id="three">3</div>

</div>

CSS:

#main{

height:200px;

border: 1px solid red;

float:left;

}

#one{

min-width:100px;

max-width:200px;

background-color:#cccccc;

height:100%;

float:left;

}

#two{

width:50px;

height: 50px;

background-color:#ccffff;

float:left;

}

#three{

min-width:100px;

max-width:200px;

background-color:orange;

height:100%;

float:left;

}

#four{

min-width:52px;

max-width:200px;

background-color:pink;

}

Please see this fiddle

Div 4 is contained in its parent div 2. Div 4 always needs to be centered from div 2 even if it gets bigger then div 2.

How to do this. At this moment the div4 is always in div2. Played around with floats, positioning and margins, but since the div 4 width is dynamical, I can never make it center.

Lets say I have entered text in div 4, then I want to let it look like this:

 _______________

| 1 |2 | 3 |

| __|___|___ |

| |div4 txt| |

| |________| |

|____|___|_____|

I hope this masterpiece makes it clear. Div4 can be bigger or smaller depending on de text in it.

If it is easier to put div2 and div4 in a new wrapper, it's fine by me, but div 1 and div 2 should always be "connected" to div 2 (also tried this, but this resulted in div 1 and div 3 to be apart from div2)

I have also tried:

  1. searching this site :)
  2. searching google
  3. margin: 0 -50%;
  4. position: relative;
  5. display: inline-block;
  6. display: tabel; (and cells)
  7. etc

Hope someone can help.

ps also div 1 and 3 aren't always displayed. ! can be hidden, 3 can be hidden but both can be hidden too

网友答案:

I think you have to use absolute positioning.

#four{
    min-width:52px;
    max-width:200px;
    width: 200px;
    background-color:pink;
    position: absolute;
    top: 50%;
    left: calc(50% - 100px)
}

See this fiddle: http://jsfiddle.net/5dh66t14/

网友答案:

You can use this CSS:

#four {
  position: relative;
  transform: translateX(-50%);
  left: 50%;
}

Working Fiddle

分享给朋友:
您可能感兴趣的文章:
随机阅读: