0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【CSS】フレキシブルボックスのアイテムの大きさを画面サイズ縮小時に固定する

Last updated at Posted at 2023-10-31

はじめに

フレキシブルボックスを使っている際、画面サイズが小さくなったときにアイテムを縮めなくするやり方を調べたのでメモです。

やり方

アイテムが縮んでしまう修正前とアイテムを縮めなくした修正後のHTMLとCSSのサンプルを記載します。

修正前

画面サイズに応じてアイテムを縮めるスタイルが適用されています。

  • 画面縮小前
    画面縮小前.png

  • 画面縮小時
    画面縮小時.png

sample.cssflex-itemクラスにflex:1;を適用することで、画面サイズを縮小すると等しく縮むアイテムになっています(詳細は参考へ)。

sample.html
<html lang="ja">
	<head>
		<title>さんぷる</title>
	<link rel="stylesheet" href="sample.css">
	</head>
	
	<body>
		<div class="flex-container">
			<div class="flex-item item1">サンプル1</div>
			<div class="flex-item item2">サンプル2</div>
			<div class="flex-item item3">サンプル3</div>
			<div class="flex-item item1">サンプル4</div>
			<div class="flex-item item2">サンプル5</div>
			<div class="flex-item item3">サンプル6</div>
		</div>
	</body>
</html>
sample.css
.flex-container{
	display: flex;
	gap: 0.5rem;
}

.flex-item{
	flex:1;

}

/* アイテムの色付け(本質じゃないです) */
.item1{
	padding:0 auto;
	background-color:red;
}

.item2{
	padding:0 auto;
	background-color:blue;
}

.item3{
	padding:0 auto;
	background-color:green;
}

修正後

sample.cssflex-itemクラスにflex-grow: 0 flex-shrink:0 flex-basis: 200px(固定したい大きさ)を指定します。
アイテムの大きさが固定したい大きさになり、コンテナの大きさがアイテムの大きさに対して足りない際はアイテムが縮まないため、アイテムの大きさが固定されます(詳細は参考へ)。

sample.css
.flex-container{
	display: flex;
	gap: 0.5rem;
}

.flex-item{
	flex:1;

}

/* 追加箇所 */
@media(max-width: 1200px){
	.flex-item{
		flex-grow: 0;
		flex-shrink: 0;
		flex-basis: 200px;/* 固定したい大きさ */
	}
}

/* アイテムの色付け(本質じゃないです) */
.item1{
	padding:0 auto;
	background-color:red;
}

.item2{
	padding:0 auto;
	background-color:blue;
}

.item3{
	padding:0 auto;
	background-color:green;
}
  • 画面縮小時
    修正後_画面縮小時.png

↑アイテムの大きさが固定されて画面サイズを縮小するとスクロールバーでスクロールが必要な状態になりました。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?