更改<div>块大小时如何实现垂直对齐

时间:2016-04-03 10:52:20

标签: html css alignment vertical-alignment

如何在更改<div>块大小时实现垂直对齐(在我的示例中 - 绿色块)。

在我的示例中需要更改的内容是,当调整浏览器窗口大小时,会出现垂直对齐(中间)边块。

vertical-align: middletop : calc(50% - 25px)属性不起作用。

实施例: http://jsfiddle.net/vsdu0cn8

我的情况和需要什么 screenshot http://www.imageup.ru/img41/2396110/example.png

代码:

<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
        font-size: 0px;
      }

      .menu-block {
        max-width: calc(2 * 75px + 7 * (50px + 2 * 5px));
        background-color: #ff8080;
      }

      .menu-block .menu-edge {
        display: inline-block;
        position: relative;
        left: 0px;
        width: 75px;
        height: 50px;
        vertical-align: top;
        background-color: #80ff80;
      }

      .menu-block .menu-container {
        display: inline-block;
        width: calc(100% - 2 * 75px);
        text-align: center;
        background-color: #ff80ff;
      }

      .menu-block .menu-container .menu-element {
        display: inline-block;
        width: 50px;
        height: 50px;
        margin: 0px 5px;
        font-size: 20px;
        background-color: #ffff80;
      }
    </style>
  </head>
  <body>
    <div class='menu-block'>
      <div class='menu-edge'></div>
      <div class='menu-container'>
        <div class='menu-element'>#1</div>
        <div class='menu-element'>#2</div>
        <div class='menu-element'>#3</div>
        <div class='menu-element'>#4</div>
        <div class='menu-element'>#5</div>
        <div class='menu-element'>#6</div>
        <div class='menu-element'>#7</div>
      </div>
      <div class='menu-edge'></div>
    </div>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

通过使用display:flex设置容器,您可以使用align-items: center来使文本垂直居中。

请参阅更新后的JSFiddle

HTML:

<div class = 'menu-block'>
    <div style="display:flex; align-items: center">
    <div class = 'menu-edge'></div>
    <div class = 'menu-container'>
      <div class = 'menu-element'>#1</div>
      <div class = 'menu-element'>#2</div>
      <div class = 'menu-element'>#3</div>
      <div class = 'menu-element'>#4</div>
      <div class = 'menu-element'>#5</div>
      <div class = 'menu-element'>#6</div>
      <div class = 'menu-element'>#7</div>
    </div>
    <div class = 'menu-edge'></div>
  </div>
</div>