jayanthCoder jayanthCoder - 3 months ago 8
CSS Question

how to force display all fixed width elements inside a div in a single line

I have fixed width elements inside a div and i need to force all the elements to be displayed on a single line with horizontal scroll bar to 'grid-content'. I have tried many things but stuck.
Here is the fiddle - https://jsfiddle.net/29pobkzf/

Here is my CSS and HTML



.grid-container {
width: 100%;
margin-top: 20px;
overflow: auto;
}

.grid-content {
width: 100%;
height: 400px;
float: left;
}
.grid-content .grid-row {
width: 100%;
overflow-x:scroll;
border-right: 1px solid #ccc;
}
.grid-content .grid-row .grid-column {
border: 1px solid #cccccc;
display: inline-block;
border-top: 0;
border-right: 0;
padding: 10px;
height: 60px;
width: 400px;
}

<div class='grid-container'>
<div class="grid-content">
<div class='grid-row'>
<div class='grid-column'>a1</div>
<div class='grid-column'>a2</div>
<div class='grid-column'>a3</div>
<div class='grid-column'>a4</div>
</div>

</div>
</div>








My intention is grid-content to have a scrollbar and all its contents occupy a single line/horizontally aligned. The problem i am facing is some elements like a3 and a4 are getting rendered below a1 and a2.

Answer

This is because .grid-column are set to display: inline-block; and will wrap onto a new line by default. This behaviour can be changed by:

  • Adding white-space: nowrap; to .grid-content .grid-row

You may also want to remove the white space between the .grid-column elements by either writing them out in one line in HTML (as in the example below) or by putting comments in between them. This will stop the white space from adding gaps between each .grid-column element in the resultant HTML.

.grid-container {
  margin-top: 20px;
  width: 100%;
}
.grid-content {
  float: left;
  height: 400px;
  width: 100%;
}
.grid-content .grid-row {
  border-right: 1px solid #ccc;
  overflow-x: scroll;
  width: 100%;
  white-space: nowrap;
}
.grid-content .grid-row .grid-column {
  border: 1px solid #cccccc;
  border-right: 0;
  border-top: 0;
  display: inline-block;
  height: 60px;
  padding: 10px;
  width: 400px;
}
<div class='grid-container'>
  <div class="grid-content">
    <div class='grid-row'>
      <div class='grid-column'>a1</div><div class='grid-column'>a2</div><div class='grid-column'>a3</div><div class='grid-column'>a4</div>
    </div>
  </div>
</div>

Comments