これは何?
ツールなどをちゃちゃっと作って公開するときにモバイル対応してないとちょっと残念。その対策のメモです。
簡単に言うと、viewportをJavaScriptで制御する、またはCSSでなんとかする方法です。
実装
CSSで何とかする
div.content
をスクリーンのサイズで動的に変えるのがポイント。
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" id="meta_viewport">
<style>
/* smaller than */
@media only screen and (max-width: 400px) {
body {
margin: 0px;
}
div.content {
width: 100%;
}
}
/* larger than */
@media only screen and (min-width: 400px) {
div.content {
width: 200px;
}
}
body {
background: #e2e1e0;
text-align: center;
font-family: arial;
display: flex;
flex-direction: column;
align-items: center;
}
div.content {
background: #fff;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
border: 1px solid #ddd;
border-radius: 5px;
height: 200px;
}
</style>
</head>
<body>
<div class="content">
Hello!
</div>
</body>
</html>
viewportで何とかする
window.onresize
のEventでviewportを動的に更新。JavaScript内の「content_width」にdiv.content
のwidth
にmargin
を考慮するのがポイント。
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" id="meta_viewport">
<style>
body {
background: #e2e1e0;
text-align: center;
font-family: arial;
display: flex;
flex-direction: column;
align-items: center;
}
div.content {
background: #fff;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
border: 1px solid #ddd;
border-radius: 5px;
height: 200px;
width: 200px;
}
</style>
</head>
<body>
<div class="content">
Hello!
</div>
<script>
const adjust_content_width = () => {
const s_width = window.outerWidth
const content_width = 220
const meta_vp = document.querySelector('meta#meta_viewport')
const content_scale = s_width/content_width < 1 ? Math.floor(100 * s_width/content_width)/100 : 1.0
meta_vp.setAttribute('content',`width=${s_width}, initial-scale=${content_scale}, maximum-scale=${content_scale}`)
}
window.onload = adjust_content_width
window.onresize = adjust_content_width
</script>
</body>
</html>