将文本垂直和水平对齐

时间:2016-12-28 06:49:23

标签: html css

如何在div内水平和垂直对齐文本?我能够与text-align:center水平对齐。但是,vertical-align不起作用。

<!DOCTYPE html>
<meta charset="utf-8">
<title></title>
<head>
    <style>
        .blocks {
          width: 200px;
          height: 100px;
          border: 1px solid black;
          text-align: center;
          vertical-align: center;
        }
        #a1 {
          margin: 0 auto;
          margin-top: 40px;
        }
        #a2 {
          float: left;
          margin-left: 25%;
        }
        #a3 {
          float: right;
          margin-right: 25%;
        }
        #a4 {
          margin: 10% auto 0;
        }
    </style>
</head>
<body>
    <div id="container">
    <div class="blocks" id="a1">some text</div>
    <div class="blocks" id="a2">some text</div>
    <div class="blocks" id="a3">some text</div>
    <div class="blocks" id="a4">some text</div>
    </div>
</body>

谢谢。

2 个答案:

答案 0 :(得分:0)

使用 css3 flexbox 概念

  • 设置父 display:flex
  • 设置子保证金:自动

它工作正常,我已添加下面的代码段。

&#13;
&#13;
<!DOCTYPE html>
<meta charset="utf-8">
<title></title>
<head>
    <style>
        .blocks {
          width: 200px;
          height: 100px;
          border: 1px solid black;
          text-align: center;
          vertical-align: center;
          display:flex;
        }
        #a1 {
          margin: 0 auto;
          margin-top: 40px;
        }
        #a2 {
          float: left;
          margin-left: 25%;
        }
        #a3 {
          float: right;
          margin-right: 25%;
        }
        #a4 {
          margin: 10% auto 0;
        }
      span{
        margin:auto;}
    </style>
</head>
<body>
    <div id="container">
    <div class="blocks" id="a1"><span>some text</span></div>
    <div class="blocks" id="a2"><span>some text</span></div>
    <div class="blocks" id="a3"><span>some text</span></div>
    <div class="blocks" id="a4"><span>some text</span></div>
    </div>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用 CSS Flexbox 。使您的.blocks成为灵活容器&amp;应用flex对齐属性align-items&amp; justify-content。像:

.blocks {
  display: flex; /* Flex Container */
  align-items: center; /* Gives Vertical Alignment */
  justify-content: center; /* Gives Horizontal Alignment */
}

查看下面的代码段(使用全屏模式):

&#13;
&#13;
.blocks {
  width: 200px;
  height: 100px;
  border: 1px solid black;
  display: flex;
  align-items: center;
  justify-content: center;
}
#a1 {
  margin: 0 auto;
  margin-top: 40px;
}
#a2 {
  float: left;
  margin-left: 25%;
}
#a3 {
  float: right;
  margin-right: 25%;
}
#a4 {
  margin: 10% auto 0;
}
&#13;
<body>
    <div id="container">
    <div class="blocks" id="a1">some text</div>
    <div class="blocks" id="a2">some text</div>
    <div class="blocks" id="a3">some text</div>
    <div class="blocks" id="a4">some text</div>
    </div>
</body>
&#13;
&#13;
&#13;

希望这有帮助!