Yamaha32088 Yamaha32088 - 6 months ago 12
HTML Question

Set width to 100 percent of text plus padding

I am having trouble getting the code below to style correctly. What I need is to have the labels be 100% width of the text inside (no word wrap) plus a fixed padding on the left and right sides. I can set a manual width using pixels but then all buttons are exactly the same width, which is not what I want. I have searched for the answer and have come up empty handed. All the solutions I tried did not work for me.

Here is a codepen: https://codepen.io/anon/pen/KzYEbv

HTML:

<div id="toolbar-upper">
<div class="sort-by-container">
<span>SORT BY </span>
<ul class="sort-by-radios">
<li>
<input type="radio" id="newest" name="sortby" value="" onchange="setLocation(this.value)">
<label for="newest">Newest Arrivals</label>
</li>
<li>
<input type="radio" id="name" name="sortby" value="" onchange="setLocation(this.value)">
<label for="name">Name</label>
</li>
<li>
<input type="radio" id="price-high" name="sortby" value="" checked="checked" onchange="setLocation(this.value)">
<label for="price-high">Price (High)</label>
</li>
<li>
<input type="radio" id="price-low" name="sortby" value="" checked="checked" onchange="setLocation(this.value)">
<label for="price-low">Price (Low)</label>
</li>
</ul>
</div>
</div>


CSS:

#toolbar-upper .sort-by-radios {
list-style-type: none;
margin: 0;
margin-left: 20px;
vertical-align: middle;
display: inline-block;
padding: 0;
}

#toolbar-upper .sort-by-radios li {
float: left;
margin: 0 15px 0 0;
height: 30px;
position: relative;
width: 130px;
}

#toolbar-upper .sort-by-radios label, #toolbar-upper .sort-by-radios input {
display: block;
position: absolute;
top: 0;
left:0;
right:0;
bottom:0;
}

#toolbar-upper .sort-by-radios input[type="radio"] {
opacity: 0.01;
z-index: 100;
}

#toolbar-upper .sort-by-radios input[type="radio"]:checked + label {
background: #3c8dc5;
color: white;
}

#toolbar-upper .sort-by-radios label {
padding: 0 30px 0 30px;
border: 1px solid #4C4C4C;
cursor: pointer;
display: inline-block;
z-index: 90;
font-weight: 600;
text-align: center;
}

#toolbar-upper .sort-by-radios label:hover {
background:#3c8dc5;
color: white;
}

#toolbar-upper .sort-by-container span {
font-size: 1rem;
display: inline-block;
vertical-align: middle;
font-weight: 600;
}

Answer

https://codepen.io/anon/pen/JXVzVx

Here's what you need. The problem was position:absolute; on the label items. I removed it, and added white-space:nowrap; to the label text, and modified the padding a little bit.

If you want to maintain position:absolute; on the rest of the elements: https://codepen.io/anon/pen/NNmJQj

ProTip: you can go padding: 5px 30px; and it means the same as padding:5px 30px 5px 30px;