Fluxian
Fluxian

Reputation: 893

Flexbox, dynamically center item

If I have a list of items, where I want to move one particular item to the center of a horizontally growing block, irregardless of DOM order. How would I go about that, with flexbox (or anything else)?

I've made an example of what I mean here:

<div id="container">
  <div id="a">A</div>
  <div id="b">B</div>
  <div id="c">C</div>
</div>

#container{
  display: flex;
  justify-content: center;
}

https://codepen.io/Slagon/pen/wvgmKBZ

Whichever of the boxes have the class .current should float the center. So for instance if C has .current, the order should be A C B. If A: B A C If B: A B C

Is this possible to do? If so, any tips on how to do it? :)

Upvotes: 3

Views: 264

Answers (1)

Temani Afif
Temani Afif

Reputation: 272909

CSS grid can do it if it's only 3 items or a known number of items

$("#container div").on("click", function(){
  $("#container div.current").removeClass("current")
  $(this).addClass("current")
})
#container{
  display: grid;
  grid-auto-flow:column dense; /* this */
  justify-content: center;
}
#container div.current{
  outline: solid 5px black;
  grid-column: 2; /* and this */
}


/* Irrelevant styling: */

#container div{
  height: 150px;
  width: 150px;
  margin: 5px;
  font-size: 55px;
  text-align: center;
  line-height: 140px;
  font-weight: bold;
}


#a{
  background: blue;
}

#b{
  background: yellow;
}

#c{
  background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <div id="a">A</div>
  <div id="b">B</div>
  <div id="c">C</div>
</div>

For an unknown number of item, you try to get that number with JS:

$(".container").each(function() {
  $(this).attr("style","--n:"+Math.round($(this).find('div').length/2));
})

$(".container div").on("click", function(){
  $(this).parent().find(".current").removeClass("current")
  $(this).addClass("current")
})
.container{
  display: grid;
  margin:10px;
  grid-auto-flow:column dense; /* this */
  justify-content: center;
}
.container div.current{
  outline: solid 5px red;
  grid-column: var(--n); /* and this */
}


/* Irrelevant styling: */

.container div{
  height: 150px;
  width: 150px;
  margin: 5px;
  font-size: 55px;
  text-align: center;
  line-height: 140px;
  font-weight: bold;
  outline: solid 5px black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div >A</div>
  <div >B</div>
  <div >C</div>
</div>

<div class="container">
  <div >A</div>
  <div >B</div>
  <div >C</div>
  <div >D</div>
  <div >E</div>
</div>

Upvotes: 1

Related Questions