如何使用flexbox将两个div并排放置,使第二个div居中? [英] How can I put two divs alongside each other keeping the second one centered using flexbox?

查看:678
本文介绍了如何使用flexbox将两个div并排放置,使第二个div居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个div:

<div class='container'>
  <div class='left'></div>
  <div class='centered'></div>
</div>

我想将第二个内部div居中,然后将第一个内部div放在居中的左边.我不希望左div粘在屏幕的左侧(如float:left那样),但相反:左div应该粘"在居中的div的左侧.

I want to center the second inner div and place the first inner div to the left of the centered one. I don't want the left div to stick to the left side of the screen (as float:left would did) but the opposite: the left div should "stick" to the left side of the centered div.

我希望使用flex进行布局,但是我愿意接受其他解决方案(不使用JavaScript,仅CSS).

I would prefer to use flex for layout, but I'm open for other solutions (without JavaScript, css-only).

推荐答案

flex容器的子代将遵循其父代对齐规则.如您所说,您需要将左元素粘贴在居中元素的左侧.因此,左元素不应与容器相关,而应与居中元素相关.

Children of flex container will follow his parent alignment rules. As you said, you need the left element to be sticked on the left of the centered one. So le left element should not be related to the container, but instead, to the centered element.

.Container {
  display: flex;
  justify-content: center;
}

.Left {
  background-color: red;
  position: absolute;
  right: 100%;
  top: 0;
}

.Centered {
  background-color: cyan;
  position: relative;
}













/* Demo only */

.Centered, .Left {
  border-radius: 4px;
  padding: 8px 24px;
}

<div class="Container"> 
  <div class="Centered">
    <div class="Left">Left</div>
    Centered
  </div>
</div>

这篇关于如何使用flexbox将两个div并排放置,使第二个div居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆