こんにちは!セミマサです。
webサイト内の要素がPC表示では横並び、スマホ表示だと縦並びになるサイトって多いですよね。あんな感じのレイアウトはフレックスボックスを使えば簡単に実現できちゃいます!
デモサイト
今回のデモサイトです。PC表示だとカードが横に、スマホ表示(画面幅480px以下)だとカードが縦に並びます。
ソースコードと解説
HTML
<section>
<div class="card-box-wrap">
<a href="#" class="card-box">
<img src="img/img1.png" alt="card-1">
<div class="card-text">
<h2>タイトル</h2>
<p>ここに内容が入ります</p>
</div>
<time><i class="fas fa-clock"></i>2019.07.24</time>
</a>
<a href="#" class="card-box">
<img src="img/img2.png" alt="card-2">
<div class="card-text">
<h2>タイトル</h2>
<p>ここに内容が入ります</p>
</div>
<time><i class="fas fa-clock"></i>2019.07.24</time>
</a>
<a href="#" class="card-box">
<img src="img/img3.png" alt="card-3">
<div class="card-text">
<h2>タイトル</h2>
<p>ここに内容が入ります</p>
</div>
<time><i class="fas fa-clock"></i>2019.07.24</time>
</a>
<a href="#" class="card-box">
<img src="img/img4.png" alt="card-4">
<div class="card-text">
<h2>タイトル</h2>
<p>ここに内容が入ります</p>
</div>
<time><i class="fas fa-clock"></i>2019.07.24</time>
</a>
<a href="#" class="card-box">
<img src="img/img5.png" alt="card-5">
<div class="card-text">
<h2>タイトル</h2>
<p>ここに内容が入ります</p>
</div>
<time><i class="fas fa-clock"></i>2019.07.24</time>
</a>
<a href="#" class="card-box">
<img src="img/img6.png" alt="card-6">
<div class="card-text">
<h2>タイトル</h2>
<p>ここに内容が入ります</p>
</div>
<time><i class="fas fa-clock"></i>2019.07.24</time>
</a>
</div>
</section>
今回のHTMLです。
CSS
.card-box-wrap{
display: flex;
justify-content: center;
align-items: center;
flex-direction: row;
flex-wrap: wrap;
padding: 2% 5%;
}
.card-box{
display: flex;
width: calc(33.3% - 20px);
flex-direction: column;
justify-content: center;
margin-right: 20px;
align-items:center;
padding: 12px;
border:solid 1px #ccc;
border-radius: 8px;
margin-bottom: 24px;
position: relative;
cursor: pointer;
box-shadow: 0 5px 10px -5px #ccc;
transition: ease-in-out .2s
}
.card-box:hover{
opacity: .7;
transform: translateY(-4px);
box-shadow: 0px 5px 15px 0px #ccc,0 0 2px 2px #ddd;
}
.card-box:nth-of-type(3n){
margin-right: 0;
}
.card-box img{
width: 100%;
}
.card-text{
display: flex;
flex-direction: column;
width: 100%;
margin-top: 12px;
margin-bottom: 24px;
}
.card-text h2{
margin-bottom: 12px;
}
.card-box time{
position: absolute;
bottom: 4%;
left: 5%;
}
@media screen and (max-width:768px){
.card-text p{
display: none;
}
.card-text h2{
margin-bottom: 0;
}
}
@media screen and (max-width: 480px) {
.card-box-wrap{
flex-direction: column;
flex-wrap: nowrap;
}
.card-box{
width: 100%;
flex-direction: column;
margin-right: 0;
}
.card-text h2{
font-size: 1.2rem;
}
.card-text p{
display: none;
}
.card-box time{
font-size: 0.9rem;
left: 4%;
}
.card-text h2{
margin-bottom: 0;
}
}
今回のCSSです。
要点は下記4点!
・.card-box-wrapのflex-directionを画面サイズに応じて切り替えるようにします!最初はrowで横並びにしておき、画面サイズ480px以下の時はcolumnで縦並びになるようにしています。
・横並びの時はflex-wrapプロパティをwrapにし、中の要素がはみ出る場合に折り返すようにしています。
・横並び時の.card-boxのwidth指定にcalc関数を使っています。マージンを考慮した横幅指定が簡単にできてとても便利です。
・横並びの時、nth-of-type(3n)で3番目と6番目のカードの右マージンを0にしています。
おわりに
フレックスボックスを使えば横並びと縦並びの切り替えが容易に実現できますね!