- 寫出以下
%
分別有多少px
:
<div class="box">
<div class="box-item"></div>
</div>
<style>
.box {
position: relative;
width: 1000px;
height: 500px;
}
.box-item {
position: absolute;
top: 50%;
bottom : 50%;
left: 50%;
right: 50%;
width: 50%;
height: 50%;
padding-top: 10%;
padding-bottom: 10%;
margin-right: 10%;
margin-top: 10%;
}
</style>
說實話忱屑,看到這道題,剛開始我是自信滿滿的壳坪,可算到后面自己就越來越不確定了舶得,為什么會出這么簡單的題呢?由此可見爽蝴,自己的基本功真不扎實呀沐批!為了展示,我加了兩個背景蝎亚,效果見CodePen
解析
- 首先明確box-item塊會相對于box塊定位珠插,并且box塊是box-item塊的包含塊;
- top, bottom, left, right, width, height, padding, margin這些屬性的值為
%
時颖对,計算的規(guī)則如下:- top, bottom, height: 基于包含元素的高度捻撑;
- left, right, width, padding-left, padding-right, margin-left, margin-right,
padding-top
,padding-bottom
,margin-top
,margin-bottom
: 基于包含元素的寬度;
- 最容易混淆以致出錯的就是
padding-top
,padding-bottom
,margin-top
,margin-bottom
,也是本題的主要考察點:margin和padding四個方向的值為%
時缤底,都是基于包含元素的寬度計算的顾患,一定要記住个唧!
答案
<div class="box">
<div class="box-item"></div>
</div>
<style>
.box {
position: relative;
width: 1000px;
height: 500px;
}
.box-item {
position: absolute;
top: 50%; /* 250px; */
bottom : 50%; /* 250px; */
left: 50%; /* 500px; */
right: 50%; /* 500px; */
width: 50%; /* 500px; */
height: 50%; /* 250px; */
padding-top: 10%; /* 100px; */
padding-bottom: 10%; /* 100px; */
margin-right: 10%; /* 100px; */
margin-top: 10%; /* 100px; */
}
</style>