實(shí)際開發(fā)中有時(shí)候會(huì)需要用到一種布局方式掩缓,即 DOM 元素的寬高始終為一特定比例。而這種布局的實(shí)現(xiàn)主要依賴于一個(gè)基礎(chǔ)的 CSS 知識點(diǎn):當(dāng) margin/padding 取形式為百分比的值時(shí)筋遭,無論是 left/right,還是 top/bottom实愚,都是以父元素的width為參照物的纬傲,比如 padding: 100% 就等于父元素的寬度。
W3C 規(guī)范
Note that in a horizontal flow, percentages on ‘margin-top’ and ‘margin-bottom’ are relative to the width of the containing block, not the height (and in vertical flow, ‘margin-left’ and ‘margin-right’ are relative to the height, not the width).
Note that percentages on ‘padding-top’ and ‘padding-bottom’ are relative to the width of the containing block, not the height (at least in a horizontal flow; in a vertical flow they are relative to the height).
大意便是贴铜,水平流中粪摘,margin、padding 的 top/bottom 百分比都是以父元素寬度為參照的阀湿;而在垂直流中赶熟,margin 的 left/right 以及 padding 的 top/bottom 的百分比則是以父元素高度為參照。
實(shí)例分析
實(shí)現(xiàn)如下布局
- A 元素左右距離10px
- A 元素在窗口水平垂直居中
- A 元素中的文字A水平垂直居中
- A 的高度始終為A寬度的50%
html.png
代碼實(shí)現(xiàn)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>寬高等比布局</title>
<style>
.parent{
overflow: hidden;
position: absolute;
left: 10px;
right: 10px;
top: 50%;
transform: translateY(-50%);
background-color: #c52121;
}
.child{
width: 100%;
padding-top: 50%;
background-color: #988f8f;
}
span{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 20px;
color: #D8D8D8;
}
img{
float: left;
margin-right: 10px;
border: 2px solid #fdf6e3;
}
</style>
</head>
<body>
<section class="parent">
<div class="child">
<span>
<img src="https://tuimeizi.cn/sexy?w=300&h=300&o=2" alt="" width="200px">測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例測試案例
</span>
</div>
</section>
</body>
</html>