- AMP:Building Accelerated Mobile Pages
- Ruadhan O'Donoghue
- 332字
- 2021-07-08 10:04:06
Using CSS3 flexbox for layout in AMP
AMP is a modern framework, and has been built with modern priorities such as performance at its core. It makes use of modern web technologies, and this includes support for CSS3 and the Flexible Box Model (flexbox). Flexbox is often regarded as an improvement over the Box Model as it doesn't use floats.
Let's see if there's a better way to achieve our desired layout with flexbox. First, remove the float:left style from the .related-thumb amp-img selector that we added in the last section. Then apply the following styles to the figure items, using .related-thumb to target them (full code at /ch3/related-flex.html):
.related-thumb {
display:flex;
align-items: center;
}
The AMP-HTML markup for our list should look like this (first two items shown):
<ul class="related-items">
<li>
<figure class="related-thumb">
<amp-img src="img/penguin.jpg" width="125" height="75" layout="fixed">
</amp-img>
<figcaption>
If a penguin can find a soul mate, I'm sure I can too
<span class="author">Rebekah Crane</span>
</figcaption>
</figure>
</li>
<li>
<figure class="related-thumb">
<amp-img src="img/cat.jpg" width="125" height="75" layout="fixed">
</amp-img>
<figcaption>
What greater gift than the love of a cat
<span class="author">Charles Dickens</span>
</figcaption>
</figure>
</li>
...
</ul>
Applying flex to the figure element means its children will expand to fill the available space. Note the use of layout="fixed" on the amp-img tags here. While we don't mind the headline stretching or shrinking to fit into the available space, we want all the images to remain the same size. (Technically though, according to the table we saw earlier, since we have already specified width and height, layout="fixed" will be inferred if the attribute is absent; we've left it in here to be explicit.)

Nearly there! It looks good on wider screens, but not so great on narrow ones, as shown in the preceding image. We also need to impose a minimum width on our images, otherwise a longer headline can affect the width of the associated thumbnail image, resulting in a nonuniform layout:
.related-thumb amp-img {
min-width: 125px;
margin-right:5px;
}
This results in a correctly aligned list on small screens, as shown in the following image:

- Visual C++串口通信開發(fā)入門與編程實踐
- Java入門經(jīng)典(第6版)
- Visual Basic程序開發(fā)(學(xué)習(xí)筆記)
- 零基礎(chǔ)玩轉(zhuǎn)區(qū)塊鏈
- C語言程序設(shè)計基礎(chǔ)與實驗指導(dǎo)
- Python 3破冰人工智能:從入門到實戰(zhàn)
- Kotlin編程實戰(zhàn):創(chuàng)建優(yōu)雅、富于表現(xiàn)力和高性能的JVM與Android應(yīng)用程序
- 深入剖析Java虛擬機:源碼剖析與實例詳解(基礎(chǔ)卷)
- ArcGIS for Desktop Cookbook
- 一步一步跟我學(xué)Scratch3.0案例
- Java 9 Programming By Example
- Groovy 2 Cookbook
- LabVIEW入門與實戰(zhàn)開發(fā)100例(第4版)
- Building Clouds with Windows Azure Pack
- R語言數(shù)據(jù)分析從入門到實戰(zhàn)