CSS百分比参照问题

一、参照父元素宽度的属性

下面例子共同的html和css

<style>
        .box{
            width: 400px;
            height: 200px;
            background-color: hotpink;
            /* 解决垂直方向外边距折叠 */
            overflow: hidden;
        }
        .box1{
            width: 50px;
            height: 50px;
            background-color: red;
        }

</style>

1.width

宽度就不需要去验证了。

2.margin

直接上代码:

<style>
    .box1{
        margin-top:25%;
    }
</style>

3.padding

<style>
    .box1{
        padding-top:25%;
    }
</style>

4.text-indent(文本缩进)

<style>
    .box1{
        text-indent:100%;
    }
</style>

 二、相对定位与绝对定位

相对定位相对最近的父元素(包含块)进行定位;绝对定位相对最近的开启定位的元素定位(包含块),如果没有父元素开启定位,则相对根标签定位(html)。

top、bottom属性值相对包含块的高度;left、right属性值相对包含块的高度。

<style>
        .box{
            width: 100px;
            height: 100px;
            background-color: hotpink;
            padding: 50px;
        }
        .box1{
            width: 50px;
            height: 50px;
            background-color: red;
            position: relative;
            top: 50%;
            left: 50%;
        }
</style>

<style>
        .wrapper{
            width: 200px;
            height: 200px;
            background-color: #bfa;
            position: relative;
        }
        .box{
            width: 100px;
            height: 100px;
            background-color: hotpink;
            padding-top: 50px;
        }
        .box1{
            width: 50px;
            height: 50px;
            background-color: red;
            position: absolute;
            top: 50%;
            left: 50%;
        }
</style>

猜你喜欢

转载自blog.csdn.net/qq_48113035/article/details/123262021