Martin Rützy
Martin Rützy

Reputation: 525

How to add horizontal scroll for flex box container?

I'm using flexbox to create a slider with horizontal slider in HTML. but with this code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container{
  width: 425px;
  display: flex;
  background-color: yellowgreen;
  overflow-x: auto;
}
.container div{
  width: 100px;
  height: 150px;
  margin: 10px;
  background-color: teal;
}
</style>
</head>
<body>

<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

</body>
</html>

all div elements get auto width and has not horizontal scroll that container box.

Upvotes: 1

Views: 124

Answers (1)

Ingo Steinke
Ingo Steinke

Reputation: 941

You can add min-width to your flex children to force keeping the desired width.

.container div {
  width: 100px;
  min-width: 100px;
}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container{
  width: 425px;
  display: flex;
  flex-direction: row;
  background-color: yellowgreen;
  overflow-x: auto;
}
.container div{
  width: 100px;
  min-width: 100px;
  height: 150px;
  margin: 10px;
  background-color: teal;
}
</style>
</head>
<body>

<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

</body>
</html>

Upvotes: 2

Related Questions