Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: how to set width to children's width?

Tags:

html

css

I want to make a horizontal section, like Quora.com

enter image description here

Here is what I come up with

<div class="out-wrapper">
  <div class="inner-wrapper">
    <% 6.times do %>
      <a class="nav-link pull-left" href="#">Nav 1</a>
    <% end  %>
  </div>
</div>

.out-wrapper{
  overflow-x: scroll;
  .inner-wrapper{
    /* width: 600px; */
    .nav-link{
      padding: 10px;
    }
  }
}

Demo: http://codepen.io/anon/pen/XJZyog

I can only create a horizontal scroll if I set the width to a fixed value.

How can I do this without specify a fixed value? Like width: overall-width-of-children So the width would automatically be the sum width of its all elements

like image 927
cqcn1991 Avatar asked Sep 04 '25 17:09

cqcn1991


1 Answers

The browser will wrap elements into new line if they extend beyond the right edge so the width of the parent element will be 100% (max). To avoid this you have two solutions:

Use display: inline-block and white-space: nowrap

.out-wrapper {
  overflow-x: scroll;
}
.out-wrapper .inner-wrapper {
  white-space: nowrap;
}
.out-wrapper .inner-wrapper .nav-link {
  display: inline-block;
  padding: 10px;
  letter-spacing: 2em; /* for demonstration */
}
<div class="out-wrapper">
  <div class="inner-wrapper">
    <a class="nav-link" href="#">Nav 1</a>
    <a class="nav-link" href="#">Nav 1</a>
    <a class="nav-link" href="#">Nav 1</a>
    <a class="nav-link" href="#">Nav 1</a>
    <a class="nav-link" href="#">Nav 1</a>
  </div>
</div>

Use display: table and display: table-cell

.out-wrapper {
  overflow-x: scroll;
}
.out-wrapper .inner-wrapper {
  display: table;
}
.out-wrapper .inner-wrapper .nav-link {
  display: table-cell;
  white-space: nowrap;
  padding: 10px;
  letter-spacing: 2em; /* for demonstration */
}
<div class="out-wrapper">
  <div class="inner-wrapper">
    <a class="nav-link" href="#">Nav 1</a>
    <a class="nav-link" href="#">Nav 1</a>
    <a class="nav-link" href="#">Nav 1</a>
    <a class="nav-link" href="#">Nav 1</a>
    <a class="nav-link" href="#">Nav 1</a>
  </div>
</div>
like image 190
Salman A Avatar answered Sep 06 '25 19:09

Salman A