【初心者向け】HTML、CSSでiframeを水平方向に中央揃えする方法3選
HTML、CSS、iframe を使って iframe を水平方向に中央揃えする方法
方法 1: display: flex と margin: auto を使用する
この方法は、最も簡単でモダンな方法です。
<div class="container">
<iframe src="https://example.com"></iframe>
</div>
.container {
display: flex;
justify-content: center;
}
方法 2: text-align: center を使用する
<div class="container">
<iframe src="https://example.com"></iframe>
</div>
.container {
text-align: center;
}
方法 3: margin: 0 auto を使用する
この方法は、iframe 自体に margin: 0 auto
を設定する方法です。
<iframe src="https://example.com" style="margin: 0 auto;"></iframe>
補足
- 上記の方法は、いずれも iframe が親要素よりも小さい場合にのみ有効です。iframe が親要素よりも大きい場合は、横にスクロールバーが表示されます。
- レスポンシブデザインに対応するには、メディアクエリを使用して、さまざまな画面サイズに応じて iframe のサイズを変更する必要があります。
- iframe のコンテンツにスクロールバーが表示されるのを防ぐには、
height
属性を設定する必要があります。
方法 1: display: flex と margin: auto を使用する
HTML
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Iframe を中央揃え</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<iframe src="https://www.youtube.com/embed/VIDEO_ID" width="560" height="315"></iframe>
</div>
</body>
</html>
CSS
.container {
display: flex;
justify-content: center;
}
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Iframe を中央揃え</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<iframe src="https://www.youtube.com/embed/VIDEO_ID" width="560" height="315"></iframe>
</div>
</body>
</html>
.container {
text-align: center;
}
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Iframe を中央揃え</title>
</head>
<body>
<iframe src="https://www.youtube.com/embed/VIDEO_ID" width="560" height="315" style="margin: 0 auto;"></iframe>
</body>
</html>
説明
- 上記のコードでは、
VIDEO_ID
を実際の YouTube 動画の ID に置き換える必要があります。 - iframe の幅と高さを必要に応じて変更できます。
- 上記のコードは、HTML ファイルと CSS ファイルを別々に作成する必要があります。
iframe を水平方向に中央揃えするその他の方法
table 要素を使用する
<table>
<tr>
<td><iframe src="https://example.com"></iframe></td>
</tr>
</table>
position: absolute と left: 50% を使用する
<iframe src="https://example.com" style="position: absolute; left: 50%; transform: translateX(-50%);"></iframe>
flexbox の justify-content: center と align-items: center を使用する
<div class="container">
<iframe src="https://example.com"></iframe>
</div>
.container {
display: flex;
justify-content: center;
align-items: center;
}
grid レイアウトを使用する
<div class="container">
<iframe src="https://example.com"></iframe>
</div>
.container {
display: grid;
place-items: center;
}
これらの方法は、それぞれ異なるメリットとデメリットがあります。最適な方法は、状況によって異なります。
その他の考慮事項
html css iframe