「CSS」positionのabsoluteで親要素を基準として要素を配置するサンプル

構文
position : 値
値 absolute
親要素を基準として要素を配置します。
親要素にはposition:relative(static以外の値であれば可)を指定します。
absoluteを使って、親要素を基準として要素を配置します。
要素は文書の通常のフローから除外され、ページレイアウト内に要素のための空間が作成されません。
直近の配置されている祖先があれば、それに対して相対配置されます。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<style>
#tt {
/*親要素*/
position: relative;
width: 150px;
height: 30px;
border: 2px solid #000;
background-color: yellow;
}
#cft {
/*子要素*/
position: absolute;
/*親要素から下*/
top: 30px;
/*親要素から右*/
left: 20px;
width: 150px;
height: 30px;
border: 2px solid #000;
background-color: green;
}
</style>
</head>
<body>
<div>親要素を基準として要素を配置するテスト</div>
<div id="tt">
parent testAA
<div id="cft">child testBB</div>
</div>
</body>
</html>
<!DOCTYPE html> <html> <head> <style> #tt { /*親要素*/ position: relative; width: 150px; height: 30px; border: 2px solid #000; background-color: yellow; } #cft { /*子要素*/ position: absolute; /*親要素から下*/ top: 30px; /*親要素から右*/ left: 20px; width: 150px; height: 30px; border: 2px solid #000; background-color: green; } </style> </head> <body> <div>親要素を基準として要素を配置するテスト</div> <div id="tt"> parent testAA <div id="cft">child testBB</div> </div> </body> </html>
<!DOCTYPE html>
<html>
<head>
<style>
  #tt {
  /*親要素*/
    position: relative;
    width: 150px;
    height: 30px;
    border: 2px solid #000;
    background-color: yellow;
  }
  #cft {
   /*子要素*/
    position: absolute;
    /*親要素から下*/
    top: 30px;
    /*親要素から右*/
    left: 20px;
    width: 150px;
    height: 30px;
    border: 2px solid #000;
    background-color: green;
  }
</style>
</head>
<body>
  <div>親要素を基準として要素を配置するテスト</div>
  <div id="tt">
    parent testAA
    <div id="cft">child testBB</div>
  </div>

</body>
</html>

説明
親要素に「position: relative」を指定します。
子要素に「position: absolute」を指定します。
親要素の辺が基準になります。

CSS

Posted by arkgame