在div中居中特定大小的div

时间:2014-10-27 19:51:29

标签: html css text-align

我尝试过在div内水平居中div的常规技巧。我一定还在做错事。查看以下jsFiddle并帮助我将“坦克”描述为“内层”标题。为方便起见,我为所有div标签添加了边框。

jsFiddle Source

HTML:

<body>
  <a href="#">
    <div class="div-inline-block" style="text-align:left;width:150px;">
      <h2>TEST</h2>
      <p>A description</p>
    </div>

    <div class="div-inline-block"><p><b>Last Update:</b><br />???</p></div>
    <div class="div-inline-block"><p><b>Flow Rate:</b><br />??? gpm</p></div>
    <div class="div-inline-block"><p><b>Inner Level:</b><br />???</p><div class="tank-level-outer"><div class="tank-level-inner"></div></div></div>
    <div class="div-inline-block"><p><b>Outer Level:</b><br />???</p></div>
    <div class="div-inline-block"><p><b>Battery Voltage:</b><br />???</p></div>
    <div class="div-inline-block"><p><b>Rainfall:</b><br />???</p></div>
    <div class="div-inline-block" style="text-align:left;width:100%;"><p><b>Notifications:</b><br />???<br />???</p></div>
   </a>
</body>

CSS:

a{
    text-decoration:none;
}
div{
    border:1px solid red;
}
.div-inline-block {
    text-align: center;
    height: 100%;
    display: inline-block;
    vertical-align: top;
    margin-left:15px;
    width: 100px;
}
.tank-level-outer {
    border:1px solid black;
    width:25px;
    height:32px;
    display:table-cell;
    vertical-align:bottom;
    margin:0 auto;
}
.tank-level-inner {
    background-color:dodgerblue;
    width:25px;
    height:25px;
}

5 个答案:

答案 0 :(得分:1)

添加此

    .div-inline-block {
    text-align: center;
    height: 100%;
    display: inline-block;
    vertical-align: top;
    margin-left:15px;
    width: 100px;
    margin:0 auto;
}
.tank-level-outer {
    border: 1px solid black;
    width: 25px;
    height: 32px;
    margin: 0 auto;
    padding: 0;
}
.tank-level-inner {
    background-color:dodgerblue;
    width:25px;
    height:25px;
    margin-top:7px;
    display: table;
    vertical-align: bottom;
}

更新小提琴

http://jsfiddle.net/czgoxafr/22/

答案 1 :(得分:0)

添加:

.tank-level-outer {
    display: table;
    margin: 0 auto;
}

答案 2 :(得分:0)

更改div .tank-level-outer的css并添加margin zero auto,删除display table-cell

.tank-level-outer {
border: 1px solid #000;
width: 25px;
height: 32px;
margin: 0px auto;
vertical-align: bottom;}

答案 3 :(得分:0)

这有效:

.tank-level-outer {
   width:25px;
   height:32px;
   display:block; // not necessary since this class is applied to a div
   vertical-align:bottom;
   margin:0 auto;
}

答案 4 :(得分:-1)

试试这个:

//css

.firstDiv{
padding:25% 25% 25% 25%
height:400px;
width:400px;
background-color:red;
}

.secondDiv{
height:200px;
width:200px;
background-color:pink;
}

//html

<div class="firstDiv">
<div class="secondDiv">
</div>
</div>