CSSのPositionでabsolute指定とかしてたら何故か他の部分にまで影響してレイアウトが崩れたので何故なのか確認してみた。

崩れた場合のサンプル

f:id:bakunyo:20130516074651p:plain

枠だけグレーの四角がinput要素(text)で、それに対し右上に絶対位置指定で色付きグレーのdiv要素(something)を置いてる。
ここまでは良いんだけど、その次に置きたい枠が緑色のdiv要素(next)が次じゃなくてinputに重なるようにして配置されてしまっている。

サンプルのソースは以下。

<!doctype html>
<html lang="ja">
<head>
<meta charSet="UTF-8">
<title>position test</title>
<style>
    .box {
      position: relative;
      width: 100px;
      height: 30px;
    }
    .text {
      position: absolute;
      width: 100px;
    }
    .something {
      position: absolute;
      right: -10px;
      top: -10px;
      width: 20px;
      height: 20px;
      background: #ccc;
    }
    .next {
      position: relative;
      width: 200px;
      height: 50px;
      border: 2px solid #2d5;
    }
</style>
</head>
<body>
<div className="box">
  <input type="text" className="text">
  <div className="something"></div>
</div>
<div className="next"></div>
</body>
</html>

修正した

色々試してみたんだけど、次のようにして解決できた。

.box {
    position: relative;
    width: 100px;
    height: 30px;   /* ←高さを指定する */
}

chromeデベロッパーツールで確認したところ、div要素(box)の高さが0となっていて、それを基準に配置していたので結果として重なってしまっていたということ。

結果もきちんと反映されました。

f:id:bakunyo:20130516074446p:plain