Html 在父 div 中居中对齐 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17587055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:59:50  来源:igfitidea点击:

Center align divs inside parent div

htmlcss

提问by msfanboy

My pen: http://codepen.io/helloworld/pen/IGsoe

我的笔:http: //codepen.io/helloworld/pen/IGsoe

I want to center align all divs with the yellow border how can I do that?

我想将所有 div 与黄色边框居中对齐,我该怎么做?

I tried margin:0 auto; on the parent container but that did not help.

我试过 margin:0 auto; 在父容器上,但这没有帮助。

The "items" with the yellow border should keep their percentage width. Do not change this to fixed pixel values.

带有黄色边框的“项目”应保持其百分比宽度。不要将其更改为固定像素值。

HTML code:

HTML代码:

<div class="table">
<div id="navigationWrapper">
<div class="table">
  <div id="left"><image width="40px" /></div>
<div id="navBar" style="width:100%; height: 100px; background-color: grey;">

  <div class="cellContainer">
        <div class="alarmTemplate">A</div>
    </div>
    <div class="cellContainer">
        <div class="alarmTemplate">B</div>
    </div>
    <div class="cellContainer">        
        <div class="alarmTemplate">C</div>
    </div>
    <div class="cellContainer">        
        <div class="alarmTemplate">D</div>
    </div> 

</div>
  <div id="right"><image width="40px" /></div>
</div>
</div>
<div id="navigationWheeler">test</div>
</div>

CSS:

CSS:

body {
  padding: 0;
  margin: 0;
  width:100%;
  height:100%;
}

.cellContainer {
    margin:0 auto;
    width: 20%;
    float: left;
    background:black;
}

.alarmTemplate{
  height:80px; 
  margin-top:10px;
  margin-bottom:10px;
  margin-left:10px;
  margin-right:10px;
  background:lightgray;
  border:yellow solid 2px;
}

#navBar, #right, #left, #navigationWheeler {
  height:80px;
  background:yellow;
  display:table-cell;
  vertical-align:middle;
 }

.table {
  display:table;
  min-width:100%;
  margin:0 auto;
}
#right, #left, #navigationWheeler {
  width:40px;
}

#navigationWheeler{
  background:green;
  text-align:center;
}

回答by feeela

To center the four DIVs set them to

要使四个 DIV 居中,请将它们设置为

.cellContainer {
    float: none;
    display: inline-block;
}

and center the navbar contents

并将导航栏内容居中

#navBar {
    text-align: center;
}

回答by Swarnamayee Mallia

Demo Linkwith corrected css

带有更正 css 的演示链接

.cellContainer {
    margin:0 auto;
    width: 20%;
    /*float: left;*/
    background:black;
    display: inline-block;
}
#navBar{
    text-align: center;
}