LoginSignup
19
15

More than 5 years have passed since last update.

position:absolute; で top と bottom の両方を効かせる

Last updated at Posted at 2015-08-07

2015年8月16日編集 情報元に誤りがあったため修正しました

結論

topbottomの両方を効かせたい要素のCSSを次のようにする
1. heightを定義しない
2. height:auto;にする

詳細

When both top and bottom are specified, and height is unspecified or either auto or 100%, both the top and bottom distances are respected. In all other situations, if height is constrained in any way, the top property takes precedence and the bottom property is ignored.

訳:topとbottomの両方が定義されていて、なおかつheightが定義されていないか、heightがauto または100%で定義されている場合、topとbottomの両方が採用される。上記に当てはまらない場合、heightが(auto /100%以外で)定義されてされていたら、topが優先されbottomは無視される。
(注:100%はMDN編集者の誤りのようです。)

つまり、次の例はbottomが無視されます。

bottomは無視される
#main {
  top: 10px;
  bottom: 20px;
  height: 90%;
}

次の例は、topとbottomにあわせて#mainのheightが柔軟に変化します。

topとbottomが有効
#main {
  top: 10px;
  bottom: 20px;
  /* height: auto; を明示的に書いても良い */
}

応用例

もともと、「<header>と<footer>を常に表示しつつ、隠れた部分をスクロールで見えるようにする」というのをやりたかったので、ついでにこのコードをメモしておきます。#targetと<header><footer>がかぶらず、かつ#targetの中身がすべてスクロールで見えるようになっています。

sample.html
<!DOCTYPE html>
<html>
<head>
  <title></title>

  <style type="text/css">
  html,body {
    padding: 0;
    margin: 0;
    height: 100%;
    width: 100%;
  }

  header {
    position: absolute;
    top: 0;
    height: 20px;
    width: 100%;
    border: solid thin blue;
  }
  footer {
    position: absolute;
    bottom: 0;
    height: 30px;
    width: 100%;
    border: solid thin green;
  }

  #target {
    position: absolute;
    top: 20px;
    bottom: 30px;
    border: solid thin red;
    width: 100%;
    overflow: auto;
  }

  </style>

</head>
<body>
  <header>header</header>
  <div id="target">
    <p>01</p>
    <p>02</p>
    <p>03</p>
    <p>04</p>
    <p>05</p>
    <p>06</p>
    <p>07</p>
    <p>08</p>
    <p>09</p>
    <p>10</p>
    <p>11</p>
    <p>12</p>
    <p>13</p>
    <p>14</p>
    <p>15</p>
    <p>16</p>
    <p>17</p>
    <p>18</p>
    <p>19</p>
    <p>20</p>
    <p>21</p>
    <p>22</p>
    <p>23</p>
    <p>24</p>
    <p>25</p>
    <p>26</p>
    <p>27</p>
    <p>28</p>
    <p>29</p>
    <p>30</p>
    <p>31</p>
    <p>32</p>
    <p>33</p>
    <p>34</p>
    <p>35</p>
    <p>36</p>
    <p>37</p>
    <p>38</p>
    <p>39</p>
    <p>40</p>
    <p>41</p>
    <p>42</p>
    <p>43</p>
    <p>44</p>
    <p>45</p>
    <p>46</p>
    <p>47</p>
    <p>48</p>
    <p>49</p>
    <p>50</p>
  </div>
  <footer>footer</footer>
</body>
</html>

この例で#targetのheightを100%にすると、bottomが無視されているように見えます。翻訳ミスでしょうか・・・ 解決しました。kura07様、ありがとうございました。

19
15
2

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
19
15