Center and stretch buttons
Stretch buttons to take up 50/50 width when container button width is unknown
by Amy Ruddy
HTML
<header>
<h1>Stretch Buttons</h1>
<p>Stretch the buttons to fill with width of the container when the width is dynamic or unkown.</p>
</header>
<section id="myButtons">
<p><span>My button container</span></p>
<div>
<button disabled>Button 1</button>
<button disabled>Button 2</button>
</div>
<button id="myCustomButton">Change button container width</button>
</section>
<code>
#myButtons div { <br>
<div class="ml">
display: flex;
</div>
}
<br><br>
button {
<div class="ml">
width: 100%;
</div>
}
<br><br>
<div class="gray_text">
//space to the right <br>
//of all but last button <br>
</div>
button:not(:last-of-type) {
<div class="ml">
margin-right: 5px;
</div>
}
</code>
SCSS
html, body {
font-family: Arial;
color: #333;
}
.gray_text {
color: #777;
}
header {
max-width: 400px;
margin: 0 auto;
text-align: center;
}
section#myButtons {
max-width: 400px;
margin: 0 auto;
border: 1px solid #4455bb;
padding: 1rem;
border-radius: 0.25rem;
margin-bottom: 1rem;
}
section {
max-width: 300px;
margin: 0 auto;
padding: .5rem 0;
p {
margin: 0;
padding: 0;
text-align: center;
background-color:white;
transform: translateY(-25px);
height: 0;
color: #4455bb;
}
span {
background-color: white;
padding: 0 0.5rem;
}
}
#myButtons div {
display: flex;
}
button {
width: 100%;
background-color: #3f51b5;
color: white;
cursor: pointer;
font-weight: 400;
vertical-align: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
border-radius: .25rem;
transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
button:not(:last-of-type) {
margin-right: 5px;
}
#myCustomButton {
max-width: 100%;
margin: 0.5rem auto 0 auto;
background-color: white;
border: 1px solid #3f51b5;
color: #3f51b5;
&:hover{
background-color: darken(#3f51b5, 10%);
box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,.075);
color: white;
}
&:focus {
outline: transparent;
}
}
code {
margin: 0 auto;
width: auto;
text-align: left;
display: table;
color: hotpink;
.ml {
margin-left: 1rem;;
}
}
JavaScript
$('#myCustomButton').click(function() {
var values = ["185", "250", "300", "350", "500"];
var value = values[Math.floor(Math.random() * values.length)];
$('#myButtons').css('width', value);
});