Dangerous Dangerous - 3 months ago 11
CSS Question

How do I present text and button elements in a td element without them wrapping?

I currently have a table listing approximately 100 products (I believe a table is what I require for the information to be displayed). At the end of each row of the table is a 'Quantity' input field followed by an 'Add To Cart' input button as shown in the following image:

enter image description here

The problem that I'm having is reducing the white space at the end of the table. I would like this column to collapse down to the width of the content without wrapping the quantity and button inputs.

The simplified html is:

<table>
<tr>
<td>Picture</td>
<td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.</td>
<td id="add-to-cart">
<input id="qty-input" type="text" value="1" />
<input id="add-to-cart-button" type="button" value="Add To Cart"/>
</td>
</tr>
</table>


And simplified css is:

table {
margin-top: 100px;
width: 100%;
border-collapse: collapse;
}

table td {
border: 1px solid #ddd;
}

#qty-input {
color: #444;
font-size: 15px;
height: 43px;
padding: 0 12px;
text-align: center;
width: 45px;
border: 1px solid #ddd;
float: left;
}

#add-to-cart-button {
background-color: #4ab2f1;
border: medium none;
color: #fff;
font-size: 15px;
height: 43px;
padding: 0 24px;
text-transform: uppercase;
float: left;
}


Note, that I added "float: left" to both of the input elements, otherwise I had a gap between the input elements as such:

enter image description here

To try to remove the gap to the right I added the following css (as mentioned in another answer):

#add-to-cart {
width: 1%;
white-space: nowrap;
}


This removes the white space but gives me another problem in that the floated fields are now wrapping:

enter image description here

Does anyone have any suggestions as to what I might be doing wrong?

Here is a jsfiddle: https://jsfiddle.net/0f6LLu0a/

Answer

You can use white-space: nowrap on #add-to-cart and remove floats. Also you can use width: 100% on second td.

table {
  margin-top: 100px;
  width: 100%;
  border-collapse: collapse;
}
table td {
  border: 1px solid #ddd;
}
#qty-input {
  color: #444;
  font-size: 15px;
  height: 43px;
  padding: 0 12px;
  text-align: center;
  width: 45px;
  border: 1px solid #ddd;
}
#add-to-cart-button {
  background-color: #4ab2f1;
  border: medium none;
  color: #fff;
  font-size: 15px;
  height: 43px;
  padding: 0 24px;
  text-transform: uppercase;
}
td:nth-child(2) {
  width: 100%;
}
#add-to-cart {
  white-space: nowrap;
}
<table>
  <tr>
    <td>Picture</td>
    <td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.</td>
    <td id="add-to-cart">
      <input id="qty-input" type="text" value="1" />
      <input id="add-to-cart-button" type="button" value="Add To Cart" />
    </td>
  </tr>
</table>