Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make div (button) 100% instead of 50% when no other buttons

Tags:

html

css

I need that when there is only one button it will be 100% width:

css based answer if it's possible here is the div's look

like image 777
alonblack Avatar asked Apr 04 '16 07:04

alonblack


People also ask

How do I make a div button full width?

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.

Can I use div instead of button?

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.

How do I fix a button size in CSS?

Tip: Use pixels if you want to set a fixed width and use percent for responsive buttons (e.g. 50% of its parent element).


2 Answers

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>
like image 177
Harry Avatar answered Oct 06 '22 00:10

Harry


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>
like image 20
Sebastian Brosch Avatar answered Oct 05 '22 22:10

Sebastian Brosch