对齐元素左和中心与flexbox [英] Aligning elements left and center with flexbox

查看:177
本文介绍了对齐元素左和中心与flexbox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用flexbox来对齐我的子元素。我想做的是使一个元素居中,并将另一个元素对齐到最左边。通常我会使用 margin-right:auto 设置左边的元素。问题是,推中心元素偏离中心。这是否可能没有使用绝对定位?

I'm using flexbox to align my child elements. What I'd like to do is center one element and leave the other aligned to the very left. Normally I would just set the left element using margin-right: auto. The problem is that pushes the center element off center. Is this possible without using absolute positioning?

HTML& CSS

#parent {
  align-items: center;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  margin: 0 auto;
  width: 500px;
}
#left {
  margin-right: auto;
}
#center {
  margin: auto;
}

<div id="parent">
  <span id="left">Left</span>
  <span id="center">Center</span>
</div>

推荐答案

flexbox的想法是提供一个框架,以容易地对齐容器内可变尺寸的元素。因此,提供一个元件的宽度被完全忽略的布局是没有意义的。从本质上讲,这正是绝对定位是什么,因为它使元素脱离正常流程。

The idea behind flexbox is to provide a framework for easily aligning elements with variable dimensions within a container. As such, it makes little sense to provide a layout where the width of one element is totally ignored. In essence, that is exactly what absolute positioning is for, as it takes the element out of the normal flow.

据我所知,没有什么好的方法这样做不使用 position:absolute; ,所以我建议使用它...但如果你真的不想,或者不能使用绝对定位然后我假设您可以使用以下解决方法之一。

As far as I know, there is no nice way of doing this without using position: absolute;, so I would suggest using it... but If you REALLY don't want to, or can't use absolute positioning then I suppose you could use one of the following workarounds.

如果您知道左div的确切宽度 justify-content flex-start (左),然后对齐中心div像这样:

If you know the exact width of the "Left" div, then you could change justify-content to flex-start (left) and then align the "Center" div like this:

#center {
    position: relative;
    margin: auto;
    left: -{half width of left div}px;
}






不知道宽度,那么您可以在右侧复制左,使用 justify-content:space-between; element:
只是为了清楚,这是真的,真的丑陋...更好地使用绝对定位比复制内容。 : - )


If you do not know the width, then you could duplicate "Left" on the right side, use justify-content: space-between;, and hide the new right element: Just to be clear, this is really, really ugly... better to use absolute positioning than to duplicate content. :-)

#parent {
  align-items: center;
  border: 1px solid black;
  display: flex;
  justify-content: space-between;
  margin: 0 auto;
  width: 500px;
}
#right {
    opacity: 0;
}

<div id="parent">
  <span id="left">Left</span>
  <span id="center">Center</span>
  <span id="right">Left</span>
</div>

这篇关于对齐元素左和中心与flexbox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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