如何实现中心点等距分布,第一项和最后一项贴边

图片描述

想要实现如图效果,每个项目中心点等距分布,但第一项的左边无空隙,最后一项右边无空隙,所有内容异步获取,数量不定,文字内容长短不等
中心点等距分布
中心点等距分布
中心点等距分布
文字内容长短不等
文字内容长短不等
文字内容长短不等

我觉得纯CSS是实现不了,有没有js能解决的办法?

求解答

阅读 3.1k
6 个回答

flex布局了解一哈
阮一峰-flex
可以给项目的父元素设置display:block,justify-content:space-between

新手上路,请多包涵

首先考虑flex布局 justify-content:space-between,兼容IE10+,
其次可以用使用margin-right,然后使用css3选择器nth-last-child将最后一个元素的margin置为0

图片描述图片描述

图片描述

是这样要效果吗?望采纳

自己写了个一看就很不优雅的方式实现吧,还是在vue里有dom操作真的是...emmm...恶心

<template>
    <div class="wrap">
        <div :style="[key == 0 && marginLeft, key == items.length - 1 && marginRight]" class="text" v-for="(item, key) in items" :key="key"><span>{{ item }}</span></div>
    </div>
</template>

<script>
export default {
    props: {
        items: {
            type: Array,
            default: () => {
                return [];
            }
        }
    },
    data() {
        return {
            marginLeft: {
                marginLeft: ''
            },
            marginRight: {
                marginRight: ''
            }
        }
    },
    mounted() {
        const texts = document.querySelectorAll('.text span');
        this.marginLeft.marginLeft = `-${texts[0].offsetLeft}px`;
        this.marginRight.marginRight = `-${texts[texts.length - 1].offsetLeft}px`;
    }
}
</script>

<style lang="less">
.wrap {
    display: flex;
    justify-content: space-between;
    .text {
        position: relative;
        flex: 1;
        text-align: center;
        &::after {
            content: '';
            position: absolute;
            left: 0;
            right: 0;
            display: block;
            margin: 5px auto;
            width: 1px;
            height: 10px;
            background: #ccc;
        }
    }
}
</style>

处理marginRight的时候还是取了offsetLeft,考虑到文字是居中的,左右的offset相同。

https://codepen.io/anon/pen/V...

flex可以的,还有一个奇葩方法兼容性好一点,放一排等宽的div,第一个text-align:left,最后一个right,中间的center,如果是文本可以考虑

在每一个子元素设定宽(足够宽,然后让内容居中),然后使用space-between或space-around实现

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题