skip to Main Content

I’m looking for a slightly modified version of the justify-content: center. Instead of justifying everything in the center I’d like to have one specific item in the center and all around it. Like in the image.

<div class="wraper">
    <span>1</span>
    <span>2</span>
    <span>Centre</span>
    <span>3</span>
</div>
.wrapper {
    display: flex;
    justify-content: center;
}

What the above code does:

enter image description here

What I need:

enter image description here

How to achieve this?

2

Answers


  1. Here is something that does what you want. In this case, the not-centered spans are child elements of the centered span, making it possible to apply relative and absolute positions to the elements. The only not-absolute one is the to-be-centered element (or actually its direct contents), the others are positioned in relation to that. Note that this only works if you apply a fixed width to the elements.


    .wrapper {
      display: flex;
      justify-content: center;
    }
    
    .wrapper span {
      background-color: #ddd;
      width: 50px;
    }
    
    .wrapper>span {
      position: relative;
    }
    
    .wrapper>span>span {
      position: absolute;
    }
    .wrapper>span>span:nth-of-type(1) {
    left: -120px;
    }
    .wrapper>span>span:nth-of-type(2) {
    left: -60px;
    }
    .wrapper>span>span:nth-of-type(3) {
    right: -60px;
    }
    <div class="wrapper">
      <span>
        <span>1</span>
        <span>2</span>
        Centre
        <span>3</span>
      </span>
    </div>
    Login or Signup to reply.
  2. Here is my best attempt at it (kind of reorganizing the elements a bit).

    * {
      box-sizing: border-box;
    }
    
    span {
      display: inline-block;
    }
    
    span:not(.inner) {
      padding: 10px;
      margin: 2px;
      background: lightgray;
    }
    
    .wrapper {
      display: flex;
      justify-content: center;
      width: 100%;
    }
    
    .inner {
      display: flex;
      flex-basis: 40%;
    }
    
    .a {
      justify-content: end;
    }
    
    .b {
      justify-content: center;
      flex-basis: 20%;
    }
    
    .b > span {
      text-align: center;
      width: 100%;
    }
    
    .c {
      justify-content: start;
    }
    <div class="wrapper">
      <span class="inner a">
        <span>1</span>
        <span>2</span>
        <span>3</span>
        <span>4</span>
      </span>
      <span class="inner b">
        <span>Center</span>
      </span>
      <span class="inner c">
        <span>5</span>
        <span>6</span>
      </span>
    </div>
    
    <div class="wrapper">
      <span class="inner a">
        <span>1</span>
        <span>2</span>
      </span>
      <span class="inner b">
        <span>Center</span>
      </span>
      <span class="inner c">
        <span>3</span>
      </span>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search