元素總是居中且高度是寬度的一半

有一個元素element, 實現如下需求:

  1. 元素e水平垂直居中
  2. 元素e水平方向與父元素保持10px間距
  3. 元素e的高度是寬度的一半
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>always-center</title>
</head>

<body>

    <div class="text-box">
        <h4>有一個元素element, 實現如下需求:</h4>
        <ul>
            <li>元素e水平垂直居中</li>
            <li>元素e水平方向與父元素保持10px間距</li>
            <li>元素e的高度是寬度的一半</li>
        </ul>
    </div>

    <style>
        html,
        body {
            height: 100%;
        }

        .element{
            position: absolute;
            margin: auto 10px;  /* 垂直方向不可定值 */
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;

            font-size: 24px;
        }

        .v-padding {
            padding-bottom: calc(50% - 10px);
            height: 0;
            background: #ddd;
        }
        .v-vw{
            height: calc( 50vw - 10px - ( 100vh - 100% ));
            background: #ccc;
        }

        .none{
            display: none;
        }

        .toggle{
            position: fixed;
            z-index: 1;
            top: 170px;
            left: 150px; 
        }

        .text-box {
            width: 400px;
            display: inline-block;
            font-size: 20px;
            position: relative;
            margin-bottom: 0;
        }
    </style>

    <button id="toggle" class="toggle"> toggle element </button>
    <div class="element none"> </div>


    <script>
        const toggle = document.getElementById('toggle');
        const cycles = [ 'v-padding', 'v-vw', 'none'];
        const element = document.querySelector('.element');
        toggle.addEventListener('click', ()=>{
            const current = cycles.shift();
            element.className = 'element '+current;
            element.innerText = current.replace('v-', '');
            cycles.push(current);
        });
    </script>



    <style>
        .padding-box {
            width: 300px;
            background: #BBB;
        }

        .padding-box .padding {
            padding: 10%;
            background: blue;
        }
    </style>

    <div class="padding-box">
        <p class="padding">
            padding 使用百分比時, 相對於父容器寬度進行計算。
        </p>
        
        <input type="range" name="padding" id="padding"> 調整父級元素寬度
    </div>
    <script>
        const r = document.getElementById('padding');
        const pbox = document.querySelector('.padding-box');
        r.addEventListener('input', () => {
            pbox.setAttribute('style', 'width: ' + (600 * r.value / 100) + 'px;');
        });
    </script>
</body>

</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章