单个主轴元素居中问题

网页html使用flex布局时对于让主轴中某一个元素相对于父级居中的情况不知道怎么解决?
想要实现的图片效果设计图:(想要实现:距离父容器两边边缘的距离都是一样的446px。)

img


其中,“前端开发工程师”(这个部分的文字可变长度),中间的“热门 初级 中级 高级”,右边的:“查看更多”分别是容器里的三个盒子。


```html
尝试:1.使用space-between,但是没有将中间的盒子居中。
     2.对中间元素使用margin:0 auto;,还是没有将中间盒子居中,因为这个margin的边界是左右两个盒子,那两个盒子的长度不同。
     3.对中间元素使用justify-self: center,样式不生效。

  

我真的不知道要怎么解决了,希望可以有高人帮帮忙!如果可以用flex相关的知识解决就更好了,没有也没关系,因为全网我搜不到思路。


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box{
      display: flex;
      justify-content: space-between;
    }
  </style>
</head>
<body>
  <div class="box">
      <div>前端工程师</div>
      <div>
         55555
      </div>
      <div>更多</div>
  </div>
</body>
</html>

这样?

img

【以下回答由 GPT 生成】

问题解决方案

要实现让主轴中的一个元素相对于父容器居中,并且距离父容器两边边缘的距离都是一样的446px,可以采用以下步骤:

  1. 在父容器的样式中,设置display: flex;来启用flex布局。
  2. 设置justify-content: space-between;来让主轴上的元素平均分布。
  3. 在主轴的两边各添加一个空的占位元素,该元素的宽度为446px并设置flex-shrink: 0;来禁止它缩小。
  4. 在中间的元素中添加一个新的父容器,并设置该父容器的样式为justify-content: center; align-items: center;来实现元素居中。
  5. 给中间元素的新父容器设置一个固定的宽度(例如800px)。

以下是具体的代码示例:

<template>
  <div class="parent">
    <div class="left"></div>
    <div class="center-container">
      <div class="center">
        <!-- 中间元素的内容 -->
      </div>
    </div>
    <div class="right"></div>
  </div>
</template>

<style>
.parent {
  display: flex;
  justify-content: space-between;
}

.left,
.right {
  flex-shrink: 0;
  width: 446px;
 }

.center-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 800px; /* 根据实际情况调整宽度 */
}

.center {
  /* 中间元素的样式 */
}
</style>

使用以上代码示例,可以实现让主轴中的一个元素相对于父容器居中,并且距离父容器两边边缘的距离都是一样的446px。请根据实际情况调整容器的宽度和中间元素的样式。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^