5
2

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.

img要素の高さにimg要素上のdiv要素の高さを合わせる

Last updated at Posted at 2020-01-20

はじめに

img要素の上にdiv要素を重ねる際の高さ合わせに時間を溶かしたので、打開策の一つを紹介します。
特定の言語・フレームワークに限った話ではないですが、今回はVue.js, Nuxt.jsで実装しました。

つまり何がしたいの?

Gif

ezgif-6-0953eabadcaa.gif

イメージ

流れ_縮小.png

div要素(赤色)の高さをimg要素(青色)の高さに合わせます。
ウィンドウサイズが変わっても追従するイメージです。

コード

<template>
  <div :style="{height:wrapperHeight}" class="wrapper">
    <img id="background-image" ref="background-image" src="./../assets/picture.png">
    <div class="flex-left" />
  </div>
</template>

<script>
export default {
  data () {
    return {
      timer: 0,
      wrapperHeight: '0px'
    }
  },
  mounted () {
    this.handleResize()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleResize () {
      const e = this.$refs['background-image']
      this.wrapperHeight = e.offsetHeight + 'px'
      if (this.timer > 0) { clearTimeout(this.timer) }
      this.timer = setTimeout(() => {
        const e = this.$refs['background-image']
        this.wrapperHeight = e.offsetHeight + 'px'
      }, 200)
    }
  }
}
</script>

<style scoped>
.wrapper{
  display: flex;
}
.flex-left{
  width:40%;
  background: #FF000099;
}
#background-image{
  z-index: -1;
  width:100%;
  position: absolute;
}
</style>

意識したこと

もっと良い方法あるぞ!って方は是非コメントなどで教えて下さい!

5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?