制作漂亮,響應(yīng)式的標(biāo)頭一直是一個(gè)棘手的過(guò)程, 直到現(xiàn)在為止你可能還需要使用 float
或者其它復(fù)雜的技巧,甚至有時(shí)還需要手動(dòng)的調(diào)整像素值广料。但現(xiàn)在不在需要這么做了!
我們將要展示的技術(shù)依賴(lài)于強(qiáng)大的 flebox
模型模式捎拯,它將為你做所有擾人的工作还栓。它只使用一些CSS屬性來(lái)創(chuàng)建一個(gè)標(biāo)題蹬挺,它適當(dāng)對(duì)齊缭乘,并在所有屏幕尺寸看起來(lái)不錯(cuò)身坐,同時(shí)保持代碼更清潔耿战,更少的hacky纽乱。
下面是效果圖
The Technique
在我們的演示示例中,我們構(gòu)建了一個(gè)標(biāo)題昆箕,它分為三個(gè)部分鸦列,其中包含嵌套在其中的典型標(biāo)題內(nèi)容:
- 左部 - 企業(yè) logo
- 中部 - 少量的超鏈接
- 右部 - 一個(gè)按鈕
下面你將看到核心部分代碼。
在 HTML
代碼中鹏倘,我們將內(nèi)容放到 div
標(biāo)簽中薯嗤,這樣將有利于 CSS
的應(yīng)用,而且通常能產(chǎn)生更有條理的代碼纤泵。
<header>
<div class="header-left">CoolLogo</div>
<div class="header-center">
<ul>
<li><a href="#">Our products</a></li>
<li><a href="#">Pricing</a></li>
<li><a href="#">Blog</a></li>
</ul>
</div>
<div class="header-right"><button>Buy now</button></div>
</header>
下面我們只需要短短幾行 CSS
代碼就可以完成整個(gè)工作骆姐。
header{
/* Enable flex mode. */
display: flex;
/* Spread out the elements inside the header. */
justify-content: space-between;
/* Align items vertically in the center. */
align-items: center;
}
完全響應(yīng)式
即使屏幕的尺寸發(fā)生變化,space-between
也仍然會(huì)按照原有的方式保持對(duì)齊捏题。 但是玻褪,當(dāng)設(shè)備的窗口對(duì)于一個(gè) header
而言比較小的時(shí)候,我們可以通過(guò)媒體查詢(xún)改變 flex-direction
屬性使其垂直對(duì)齊公荧。
@media (max-width: 1000px){
header{
/* Reverse the axis of the header, making it vertical. */
flex-direction: column;
/* Align items to the begining (the left) of the header. */
align-items: flex-start;
}
}
總結(jié)
為了解更多關(guān)于 flexbox
和教程中使用到的 CSS
屬性带射,可以查看這些連接: