将宽度设置为文本的100%加上填充

时间:2016-05-15 20:10:30

标签: html css

我无法正确使用下面的代码。我需要的是让标签内部文本的宽度为100%(没有自动换行)加上左侧和右侧的固定填充。我可以使用像素设置手动宽度,但所有按钮的宽度完全相同,这不是我想要的。我已经找到了答案并空手而归。我试过的所有解决方案都不适用于我。

这是一个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;
}

1 个答案:

答案 0 :(得分:1)

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

这就是你需要的。标签项上的问题是position:absolute;。我删除了它,并将white-space:nowrap;添加到标签文本中,并稍微修改了填充。

如果您想在其余元素上维护position:absolute;https://codepen.io/anon/pen/NNmJQj

ProTip:您可以padding: 5px 30px;,它与padding:5px 30px 5px 30px;

相同