0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

marginを使って中央揃えできなかったときの対処法

Posted at

Zennで記事をよく書いていますので、そちらもよければご覧ください。

はじめに

CSS で margin を使ったときに中央揃えができなかったときに調べたことを記載しました。

  • 修正前のソースコード
div {
  margin: 0 auto;
  background-color: yellow;
}

CSS修正前

原因

margin:0 auto;を使ったときに中央揃えできないときは下記を確認します。

  • ブロックレベルの要素に対して指定しているか
  • width の指定をしているか

margin はブロックレベルの要素に対して指定するが、ブロックレベルだとデフォルトで width は 100%となっているため親要素の幅いっぱいに広がっています。width を指定することで(親要素の幅 - 要素の幅)が左右にできるため auto で左右の余白を均等に分配され、中央に配置されます。

  • ソースコード
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>
  </head>
  <body>
    <div>text1</div>
  </body>
</html>
div {
  margin: 0 auto;
  width: fit-content; /*コンテンツのサイズに基づいて適切な幅を指定*/
  background-color: yellow;
}

CSS修正後

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?