Flexbox:居中元素,两侧均带有空格 [英] Flexbox: centered element with space-around elements on either side

查看:72
本文介绍了Flexbox:居中元素,两侧均带有空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用flexbox设置一个菜单,该菜单由七个具有不同宽度的<li>元素组成.我希望我的中间(源顺序中的第4个)<li>元素始终水平居中作为锚点,第1-3个<li>元素占据居中的<li>左侧的空间,并且第5-7号占据了右边的空间.

I'm using flexbox to set up a menu consisting of seven <li> elements with various widths. I'd like my middle (4th in the source order) <li> element to always be horizontally centered as a sort of anchor, with the 1-3rd <li> elements occupying the space to the left of the centered <li> and the 5th-7th occupying the space to the right.

我在父级flex容器上尝试过space-aroundspace-between以及在我要居中的<li>元素上尝试过align-self: center,但到目前为止还没有运气.来自flexbox知识渊博的人的任何帮助将不胜感激.

I've tried space-around, space-between on the parent flex container as well as align-self: center on the <li> element I'm trying to center, but so far no luck. Any help from someone knowledgeable in flexbox would be appreciated.

jsfiddle

推荐答案

您需要修改nav结构,并从3个容器 left center right . 演示

You need to modify your nav structure and start from 3 containers left, center and right. DEMO

HTML

left right 将包含一些链接, center 是一个链接.

left and right will hold a few links, center is a link.

<nav>
<span>
    <a href="#">aaa </a>
    <a href="#">aa </a>
    <a href="#">a </a>
    </span>
    <a href="#"> center </a>
    <span>
      <a href="#">bbbb </a>
      <a href="#">bbbbb </a>
      <a href="#">bbbbbb </a>
    </span>
</nav>


CSS

nav将采用display:flexjustify-content:space-between left right 也是如此.

nav will take display:flex and justify-content:space-between, so will left and right.

nav, nav span {
    display:flex;
    justify-content:space-between;
    flex-wrap:wrap;/* so they do not overlap each other if space too short */
}

要在 right left 的中心位置产生间隙,我们只需添加一个伪元素(或一个空元素).

To generate a gap at edges of right and left towards center, we just add a pseudo element (or an empty element).

span:first-of-type:after,
span:last-of-type:before{
    content:'';
    display:inline-block;/* enough , no width needed , it will still generate a space between */
}

left right 可以采用比1 flex值,以避免 center 扩展太多.

left and right can take a flex value higher than 1 , to avoid center to expand too much.

nav > span {
    flex:2; /* 2 is minimum but plenty enough here  */
}

让我们绘制链接框:

a {
    padding:0 0.25em;
    border:solid;
}


演示


DEMO

这篇关于Flexbox:居中元素,两侧均带有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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