Aravind Aravind - 4 months ago 6
CSS Question

Aligning div's horizontally in a line

I came across a scenario in which i have a parent container and inside that there will be a number of div's, which i need to display in one line.

The requirements are:


  1. The number of div's will change

  2. the width of each of the item's will differ

  3. There should be a horizontal scroll bar in which we can swipe and select items.



I have tried with multiple solutions, but nothing is working as expected. When I tried with
display:inline-table
for child div's, it is working in PC and but fails in Iphone.

The code looks like:



.container {
background-color: #fff;
border-top: 1px solid grey;
display: flex;
overflow: -moz-scrollbars-none;
overflow-x: scroll !important;
}
.child {
display: inline-table;
}

<div class="container">
<div class="child">Shirt</div>
<div class="child">Jeans</div>
.
.
.
.
.
.
<div class="child">Swetter</div>
<div class="child">T-shirts<div>
<div>





Can anyone help me out to solve this?

Answer
  • I have used white-space: nowrap; for the parent which align the child elements horizontally by adding a scrollbar
  • Any no of child can be there and the width can be different in below example i have used the width of the content using display:inline-block

.parent {
  border: 1px solid green;
  overflow: auto; /* change to overflow-x: scroll if you want to show scrollar if less elements */
  padding: 5px;
  white-space: nowrap;
}
.parent > div {
  border: 1px solid red;
  display: inline-block;
  padding: 5px;
}
<div class='parent'>
  <div>one</div>
  <div>threeeee</div>
  <div>fiveeeeeeeeee</div>
  <div>one</div>
  <div>threeeee</div>
  <div>fiveeeeeeeeee</div>
  <div>one</div>
  <div>threeeee</div>
  <div>fiveeeeeeeeee</div>
  <div>one</div>
  <div>threeeee</div>
  <div>fiveeeeeeeeee</div>
  <div>one</div>
  <div>threeeee</div>
  <div>fiveeeeeeeeee</div>
  <div>one</div>
  <div>threeeee</div>
  <div>fiveeeeeeeeee</div>
</div>

Comments