开发者

Horizontal alignment of 3 boxes in a wrapper

开发者 https://www.devze.com 2023-03-09 13:31 出处:网络
Hey, I\'m playing around with CSS3 at the moment and ran into a problem, using three div boxes. I want them to be horizontally aligned in a wrapper box without having to specify the exact margins.

Hey, I'm playing around with CSS3 at the moment and ran into a problem, using three div boxes. I want them to be horizontally aligned in a wrapper box without having to specify the exact margins.

My approach has been this:

.box1 {
background: gray;
float: left;
width: 250px;
padding: 3px;
margin: 0 auto;
}

.box2 {
background: gray;
float: left;
width: 250px;
padding: 3px;
margin: 0 auto; 
}

.box3 {
background: gray;
float: left;
width: 250px;
padding: 3px;
margin: 0 auto;
}

which results i开发者_运维百科n the three boxes, aligned left to wrapper box without any margins between them. But I want the boxes to set the margins, so the boxes are centered in the red wrapper. Any ideas to do this without exact pixel settings?


Hmm. Well you can't use margin-auto on floated values. I'd give them exact pixel margins. More control.

Do you expect to not know the width of the red-wrapper?

Also, all those classes are the same, just call it "box" and reuse that for all your boxes.

.box{
  background: gray;
  float: left;
  width: 250px;
  padding: 3px;
  margin: 3px;
}

<div id="red-wrapper">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

EDIT: (was thinking about this. Thought I'd share a different structure that might give you the results you're looking for.)

.bigbox{
  width:33%;
  float:left;
}

.box {
  background: gray;
  width: 200px;
  padding: 3px;
  margin: 3px auto;
}

#red-wrapper {
  width:100%;
  background:red;
  overflow:hidden;
}

<div id="red-wrapper">
  <div class="bigbox">
    <div class="box"> </div>
  </div>
  <div class="bigbox">
    <div class="box"></div>
    </div>
  <div class="bigbox">
    <div class="box"></div>
  </div>
</div>

jsFiddle


If its suitable for your purpose, inline-block might help. Fiddle.


I had this problem and I used Flex box. https://www.w3schools.com/css/css3_flexbox.asp you can wrap it to fit elements when zooming in.

0

精彩评论

暂无评论...
验证码 换一张
取 消