0
1

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 5 years have passed since last update.

innerからの脱獄2

Last updated at Posted at 2020-02-13

画面端まで中身を伸ばす

前回innerより横幅の広い要素を中央揃えにする方法を紹介しました。
今回は幅が決まっていない場合はどうすればいいのかを紹介します。

元の状態

See the Pen WNvrNRe by sphenisc (@sphenisc) on CodePen.

画面幅いっぱいまで広げると

See the Pen WNvrNpe by sphenisc (@sphenisc) on CodePen.

こうなります。 中身の領域を変えずに背景だけ広げたいならその要素に
padding: 0 calc(50vw - 50%);
margin: 0 calc(50% - 50vw);

をつけます。何をしているかというと
例えばディスプレイの画面幅が1920px 広げたい要素の横幅が980pxだとすると

  • margin: 980pxの50%で490px - 1920pxの半分の960px = -470px 左右に470pxのマイナスマージンをとる。つまり横幅が470px×2 だけ広くなる
  • padding: 960px - 490px = 470px 左右に470pxの余白ができる
    (NormalizeCSSの影響で box-sizing: border-box; が適用されている)

→中身の領域は変えず、背景だけを画面幅いっぱいにすることができるわけです。
中身も含めて画面幅いっぱいにしたい場合は padding: 0 calc(50vw - 50%); を消すだけで修正できます。

活用例

タイトルの装飾を左端または右端まで伸ばす

See the Pen OJVMJpG by sphenisc (@sphenisc) on CodePen.

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?