Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

CSS center div child of two pairs of divs

I'm back with another probably lame CSS question.

So I have a container div, two paired divs within it, and each of them has two more divs. I want to justify all four with equal space between them.

What I have at the moment:

html:

<div class="container">
    <div class="pairsWithinContainer">
        <div>
        </div>
        <div>
        </div>
    </div>
    <div class="pairsWithinContainer">
        <div>
        </div>
        <div>
        </div>
    </div>
</div>

css:

.container {
  width: 100%;
  height: 200px;
  background-color: blue;
  padding: 2px;
}

.container > div {
  display: inline-block;
  width: 49.5%;
  height: 200px;
  background-color: yellow; 
}

.pairsWithinContainer > div {
  display: inline-block;
  background-color: green;
  width: 50px;
  height: 100%;
}

JSFiddle: https://jsfiddle.net/tyzdhzt2/9/

What I want to do: http://sketchtoy.com/67874588

People who know CSS, help please.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'd recommend doing this with display:flex instead of display:inline-block.

Setting the containers to be flex boxes will automatically move your content into one line. flex-direction:row will make this line a row, flex-direction:column will make it a column. Use justify-content:space-around to have the container box distribute even space around all it's children.

To have the first row of containers wrap when the browser shrinks, give those boxes a min-width property and give their wrapping element flex-wrap:wrap like so:

.container {
  width: 100%;
  height: auto;
  background-color: blue;
  padding: 2px;
  display:flex;
  justify-content:space-around;
  flex-wrap:wrap;
}

.container > div {
  display: flex;
  justify-content:space-around;
  width: 49.5%;
  height: 200px;
  min-width:400px;
}

.pairsWithinContainer > div {
  background-color: green;
  width: 50px;
  height: 90%;
}
<div class="container">
    <div class="pairsWithinContainer">
        <div>
        </div>
        <div>
        </div>
    </div>
    <div class="pairsWithinContainer">
        <div>
        </div>
        <div>
        </div>
    </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...