Appearance
イメージ下のテキスト位置を相対的に固定したい
グリッドを使ってディスプレイサイズに応じたレイアウトをすることがありますが、テキスト位置をイメージに追従させたい場合があります。
サンプル1
以下のサンプルでは、イメージ下のテキストの位置が親の幅に依存しているため、イメージに対して位置を固定できておりません。
試しに、ディスプレイ幅を狭めてみてください。
テキストの位置がイメージに対して固定されていないことがわかります。
INFO
視認しやすくするため、テキストの背景色を変更しています。
Item 1
Item 2
Item 3
サンプルコード
vue
<template>
<v-container>
<v-row>
<v-col v-for="item in items" cols="12" md="6">
<v-img src="https://cdn.vuetifyjs.com/images/cards/desert.jpg"></v-img>
<p class="text">{{ item }}</p>
</v-col>
</v-row>
</v-container>
</template>
vue
<script setup lang="ts">
const items = [
"Item 1",
"Item 2",
"Item 3",
]
</script>
vue
<style scoped>
.v-img {
max-width: 300px;
margin-bottom: 16px;
display: 'flex';
margin: 0 auto;
}
.text {
display: 'flex';
margin: 0 auto;
color: red;
background-color: gray;
text-align: start;
padding: 0 32px;
}
</style>
イメージに対してテキスト位置を相対的に固定する方法
イメージ下のテキスト位置を固定表示する方法を紹介します。
解決方法としては、テキスト幅をイメージ幅に指定します。 こうすることで、テキスト幅が親の幅に依存しなくなるため、調整がしやすくなります。
サンプル2
以下のサンプルでは、イメージ下のテキスト位置をイメージに対して固定表示しています。
Item 1
Item 2
Item 3
サンプルコード
vue
<template>
<v-container>
<v-row>
<v-col v-for="item in items" cols="12" md="6">
<v-img src="https://cdn.vuetifyjs.com/images/cards/desert.jpg"></v-img>
<p class="text">{{ item }}</p>
</v-col>
</v-row>
</v-container>
</template>
vue
<script setup lang="ts">
const items = [
"Item 1",
"Item 2",
"Item 3",
]
</script>
vue
<style scoped>
.v-img {
max-width: 300px;
margin-bottom: 16px;
display: 'flex';
margin: 0 auto;
}
.text {
/* max-widthを指定してイメージと同じ幅にしています */
max-width: 300px;
display: 'flex';
margin: 0 auto;
color: red;
background-color: gray;
text-align: start;
padding: 0 32px;
}
</style>