Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to horizontally stretch elements when using flex-box

Tags:

css

flexbox

web

I am trying to strech inner objects horizontally so they will fill the width of their container.

here is my code:

<!DOCTYPE html>
<html>
<head>
<style>
.flex-container {
  display: flex;
  height: 200px;
  align-items: stretch;
  background-color: DodgerBlue;
}

.flex-container > div {
  background-color: #f1f1f1;
  margin: 10px;
  text-align: center;
  line-height: 75px;
  font-size: 30px;
}
</style>
</head>
<body>
<h1>The align-items Property</h1>

<p>The "align-items: stretch;" stretches the flex items to fill the container (this is default):</p>

<div class="flex-container">
  <div>1</div>
  <div>2</div>
  <div>3</div>  
</div>

</body>
</html>

The height of the inner div elements stretched thanks to the property:

align-items: stretch;

How to stretch the width of these elements too?

like image 440
GyRo Avatar asked Mar 07 '26 08:03

GyRo


2 Answers

Just add flex:1 to flex items:

.flex-container {
  display: flex;
  height: 200px;
  align-items: stretch;
  background-color: DodgerBlue;
}

.flex-container > div {
  background-color: #f1f1f1;
  margin: 10px;
  text-align: center;
  line-height: 75px;
  font-size: 30px;
  flex: 1;
}
<h1>The align-items Property</h1>

<p>The "align-items: stretch;" stretches the flex items to fill the container (this is default):</p>

<div class="flex-container">
  <div>1</div>
  <div>2</div>
  <div>3</div>  
</div>

This guide could be very helpful for you: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

like image 144
ReSedano Avatar answered Mar 09 '26 22:03

ReSedano


You are using flexbox with the default flex-direction: row. Which places the elements in a row and ajusts their width based on their initial width and flex properties.

This means that align-items: stretch; will stretch the items in such manner so they so they fit the parent element but not in width, but in height. since their width is defined by the flex property;

use flex: 1 1 auto; to make the element fit it's parent.

See https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for more details.

like image 33
kamentk Avatar answered Mar 09 '26 23:03

kamentk



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!