I need that when there is only one button it will be 100% width:
css based answer if it's possible
display: block and width: 100% is the correct way to go full width but you need to remove the left/right margin on the button as it pushes it outside the containing element. for more information on the box-sizing property, read the MDN docs.
You should use <a> or <button> , not <div> . an anchor with an href attribute will trigger page reload. Without an href, it is not "tabable", and it still does not carry the button semantic. <a role="button" tabindex="0"></a> does all that.
Tip: Use pixels if you want to set a fixed width and use percent for responsive buttons (e.g. 50% of its parent element).
You can make use of the :only-of-type
selector to override the width
property like in the below snippet.
.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;
}
<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>
You can use flexbox to solve this problem:
.buttons {
display:flex;
flex-direction: row;
align-items:stretch;
}
.btn {
border:1px solid #000;
text-align:center;
width:100%;
}
<div class="buttons">
<div class="btn">Test</div>
<div class="btn">Test</div>
</div>
<div class="buttons">
<div class="btn">Test</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With