LoginSignup
1
0

More than 3 years have passed since last update.

特定要素のwidth基準のサイズ指定 by css&js

Last updated at Posted at 2020-02-08

vwは便利ですけど、画面全体の幅基準なので、responsiveに幅の変化する要素を基準にはできませんね。
以下はそれをjsで実現するものです。

css
:root{
   --base1: 0;
}

.title-box{
   position:relative;
}

.welcome{
   font-size: calc(var(--base1) * 8vw);
   margin-top: calc(var(--base1) * 17vw);
}
.title{
   font-size: calc(var(--base1) * 12vw);
   line-height: calc(var(--base1) * 12vw);
   margin-top: calc(var(--base1) * 3vw);
}
html
<div data-calc-base="base1" class="title-box" >
   <div class="welcome">ようこそ!</div>
   <div class="title" >種子島へ!</div>
   <img src="/img/tanegasima/top.jpg" >
</div>
js
$(window).on('load resize', ()=>{
   $('[data-calc-base]').each(function(){
      document.documentElement.style.setProperty(
         '--' + $(this).data('calc-base'), $(this).width() / $(window).width()
      );
   });
});

inspired by
https://flex-font.com/how_to/

1
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
1
0