如果没有其他按钮,如何使div(按钮)100%而不是50%

alo*_*ack 4 html css css3

我需要的是当只有一个按钮时它将是100%宽度:

如果可能的话,基于CSS的答案 这是div的样子

Har*_*rry 8

您可以使用:only-of-type选择器覆盖width属性,如下面的代码段所示.

.container {
  width: 200px;
  height: 50px;
  border: 1px solid red;
}

/* if button is input tag */
input[type='button'] {
  float: left;
  width: 50%;
  border: 1px solid green;
  background: blue;
  color: white;
}
input[type='button']:only-of-type {
  width: 100%;
  background: blue;
  color: white;
}

/* if button is button tag */
button {
  float: left;
  width: 50%;
  border: 1px solid green;
  background: blue;
  color: white;
}
button:only-of-type {
  width: 100%;
  background: blue;
  color: white;
}
Run Code Online (Sandbox Code Playgroud)
<h4>For Buttons using input tag</h4>
<div class='container'>
  <input type='button' value='Button 1' />
  <input type='button' value='Button 2' />
</div>
<div class='container'>
  <input type='button' value='Button 1' />
</div>

<h4>For Buttons using buton tag</h4>

<div class='container'>
  <button>Button 1</button>
  <button>Button 2</button>
</div>
<div class='container'>
  <button>Button 1</button>
</div>
Run Code Online (Sandbox Code Playgroud)