【问题标题】:2 divs aligned to each other and centered in viewport stop being aligned in smaller viewports2 个 div 彼此对齐并在视口中居中停止在较小的视口中对齐
【发布时间】:2019-08-18 21:39:29
【问题描述】:

我有一个使用转换在视口中垂直和水平居中的登录框,我想在该登录框旁边添加一个简单的菜单,但在它之外(2 个 div 彼此相邻)。第一个 div(登录框)有一个静态宽度,我使用浮动对齐它们,它有点工作,但一旦视口宽度变小就停止工作 - 然后 div 被放在另一个下面,即使还有空间留在视口中。

尽管视口宽度不同,我怎样才能让它们保持这种状态?我还想将侧边菜单垂直居中于登录框。

这是一个非常简单的小提琴说明问题:

body {
  height: 100vh;
  width: 100vw;
}

.center-container {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
}

.a {
  background-color: red;
  width: 300px; /* increase the width and .b goes under .a */
  height: 60px;
  float: left;
}

.b {
  display: inline-block;
  float: right;
}
<div class="center-container">
  <div class="a">
    Test
  </div>
  <div class="b">
    <ul>
     <li>Li 1</li>
     <li>Li 2</li>
    </ul>
  </div>
</div>

【问题讨论】:

    标签: html css


    【解决方案1】:

    抛弃浮动并检查 flexbox...你永远不想回去。我经常推荐这个指南:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

    旁注:我在 div.b 标记中添加了 min-width: 70px 以及文本换行...white-space: nowrap 可能也可以在那里使用

    body {
      height: 100vh;
      width: 100vw;
    }
    
    .center-container {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
      display: flex;
      
    }
    
    .a {
      background-color: red;
      width: 600px; 
      height: 60px;
    }
    
    .b {
      display: inline-block;
      min-width: 70px
    }
    <div class="center-container">
      <div class="a">
        Test
      </div>
      <div class="b">
        <ul>
         <li>Li 1</li>
         <li>Li 2</li>
        </ul>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 2014-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多