Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: 100% width minus element on same line

Tags:

html

css

How would I make an input element 100% width that is available? So, 100% width minus the width of any other elements on the same line (not knowing the width of those elements)?

.bg {
  padding: 20px;
  background: #f5f5f5;
  margin-bottom: 25px;
 }
input {
  width: 100%;
  padding: 0.4em;
  height: 25px;
  border: 1px solid #ccc;
}
.button {
  height: 25px;
  padding: 0.4em;
  background: #ccc;
  border: 1px solid #ccc;
  text-decoration: none;
 }
<div class="bg">
  
  <input type="text" placeholder="100% width - button" /><a class="button" href="#">Click</a>
  
 </div>

<div class="bg">
  
  <input type="text" placeholder="100% width" />
  
 </div>
like image 401
MultiDev Avatar asked Sep 06 '26 09:09

MultiDev


2 Answers

2 ways do that:

  • use flexbox, applying display:flex in .bg (.bg2 for demo) and flex:1 (or just flex-grow:1) in input

.bg {
  padding: 20px;
  background: #f5f5f5;
  margin-bottom: 25px;
}
.bg2 {
  display: flex;
  border: solid red
}
.bg2 input {
  flex: 1;
}
input {
  width: 100%;
  padding: 0.4em;
  height: 25px;
  border: 1px solid #ccc;
}
.button {
  height: 25px;
  padding: 0.4em;
  background: #ccc;
  border: 1px solid #ccc;
  text-decoration: none;
}
<div class="bg bg2">

  <input type="text" placeholder="100% width - button" /><a class="button" href="#">Click</a>

</div>

<div class="bg">

  <input type="text" placeholder="100% width" />

</div>
  • For older versions of IE, use CSS tables

* {
  box-sizing: border-box
}
.bg {
  padding: 20px;
  background: #f5f5f5;
  margin-bottom: 25px;
  display: table;
  width: 100%;
}
input {
  display: table-cell;
  width: 100%;
  padding: 0.4em;
  height: 25px;
  border: 1px solid #ccc;
}
.button {
  display: table-cell;
  height: 25px;
  padding: 0.4em;
  background: #ccc;
  border: 1px solid #ccc;
  text-decoration: none;
}
<div class="bg bg2">

  <input type="text" placeholder="100% width - button" /><a class="button" href="#">Click</a>

</div>

<div class="bg">

  <input type="text" placeholder="100% width" />

</div>
like image 132
dippas Avatar answered Sep 07 '26 22:09

dippas


Adding display:flex to the .bg-class works. Flexbox tries to evenly distribute it's child-elements, but since one of the elements has 100% width and there's still another child, the width is adjusted, so everything fits in one row. There is a great guideline for the flex-attribute here.

like image 41
Thomas Altmann Avatar answered Sep 07 '26 21:09

Thomas Altmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!