3
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?

More than 3 years have passed since last update.

【CSS】子要素「僕に逆らう奴は親(要素)でも〇す」

Last updated at Posted at 2020-11-13

概要

長く生きていると親要素から子要素をはみ出させたい時がくると思います
今回は大きく分けて2通りのやり方ではみ出させてみようと思います

もとの要素はこんな感じ

もとの要素

方法1:ディスプレイ幅に合わせて調整

子要素にvw(viewport width)で、100vwを指定するとウィンドウの幅いっぱいになります

これだけだと、開始位置が親要素に依存するのでズレちゃいます

子要素の開始位置が親要素に依存している

こんな感じに指定すると

.child1 {
  width: 100vw;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}

子要素の開始位置が親要素に依存しなくなった

コード

oyakoro.html
<div class="parent1">
  parent1
  <div class="child1">child1</div>
</div>
oyakoro.scss
.parent1 {
  text-align: center;
  color: white;
  background-color: #57d1c9;
  width: 50%;
  margin: 12px auto;
  padding: 12px;
  height: 400px;
  > .child1 {
    background-color: #ed5485;
    height: 200px;
    width: 100vw;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
  }
}

方法2:ネガティブマージンを利用

ネガティブマージンとは、marginに、マイナスの数値を指定することです

画像の上に文字を載せたい時などに使われる気がします

方法2-1:calc()を利用

子要素に下記を指定

.child2 {
  margin: 0 calc(((100vw - 100%) / 2) * -1);
}

ネガティブマージンによって、親要素と子要素の幅が相殺される

コード

oyakoro.html
<div class="parent2">
  parent2
  <div class="child2">child2</div>
</div>
oyakoro.scss
.parent2 {
  text-align: center;
  color: white;
  background-color: #0072bb;
  width: 50%;
  margin: 12px auto;
  padding: 12px;
  height: 400px;
  > .child2 {
    height: 200px;
    background-color: #ff4c3b;
    margin: 0 calc(((100vw - 100%) / 2) * -1);
  }
}

方法2-2:力技で幅を広げる

子要素に下記を指定

.child3 {
  margin: 0 -100%;
}

ネガティブマージンで横幅を広げて要素をはみ出させている

コード

oyakoro.html
<div>
  <div class="parent3">
    parent3
    <div class="child3">child3</div>
  </div>
</div>
oyakoro.scss
.parent3 {
  text-align: center;
  color: white;
  background-color: #09194f;
  width: 50%;
  margin: 12px auto;
  padding: 12px;
  height: 400px;
  > .child3 {
    height: 200px;
    background-color: #f9ce00;
    margin: 0 -100%;
  }
}

他に良いやり方あったら教えてくれると嬉しいです

3
0
1

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
3
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?