前言
好幾個月沒有更新了,也側面反應工作太忙。最近被各種List的樣式折磨得不輕。看似樣式簡單,但是在實現時也遇到不少問題。這篇小文記錄一下,也提供給遇到相似問題的同學。
1. List圖片環繞
(1) 目標
如圖,實現這樣一個效果:
- List環繞在圖片周圍
- List的點始終和段落對齊,且在內容的外部
(2) 分析和實現
實現文字環繞,需要將圖片設置浮動float: left
。
原點始終在文字外,所以list-style: outside
(這個是默認的,所以不用設置)。
進行了這些操作以後,效果如下:
現在需要做的是移動list的位置,在圖右邊的需要往右移動,而在圖下方的需要往左移動。這就產生了一個矛盾,我們並不知道動態內容的情況下,哪些內容會在右,哪些會在下方。
如何解決呢?我們將兩部分調整到一致狀態。
下方的間隙的產生是由於瀏覽器自動對ul
設置了padding-inline-start: 40px;
,另外設置margin只對下方有效,右方的無效。所以可以設置margin-left: -40px
將右方和下方的調整到一致。
現在唯一要做的是將list整體右移。上面提到了,margin對右側的不奏效,同理也不能使用padding。最簡單的是通過設置position: relative; left: 1em
,利用相對定位不脫離文檔流的方式移動list。同樣transform: translateX(1em);
也奏效。
demo: https://jsfiddle.net/doyk9hx1/1/
<div class="artical">
<img src="https://via.placeholder.com/150" alt="">
<p>You can get prescriptions filled at any of our 24 Kaiser Permanente pharmacies.</p>
<ul>
<li>You can get prescriptions filled at any of our 24 Kaiser Permanente pharmacies. </li>
<li>You can also get a 90-day supply refilled at a reduced copay through mail order, and have them delivered right to your home with no cost for shipping.</li>
<li>You can get prescriptions filled at any of our 24 Kaiser Permanente pharmacies. </li>
<li>You can also get a 90-day supply refilled at a reduced copay through mail order, and have them delivered right to your home with no cost for shipping.</li>
</ul>
<p>
You can also get a 90-day supply refilled at a reduced copay through mail order, and have them delivered right to your home with no cost for shipping.
</p>
</div>
.artical{
width: 400px;
font-size: 16px;
}
img{
float: left;
margin: 0 20px 10px 0;
}
li{
position: relative;
left: 1em;
margin-left: -40px;
}
(3) 解決IE兼容問題
其他瀏覽器顯示都是好的,唯獨IE即便是在高版本下,也呈現如下樣子:
經過嘗試發現,IE並不支持list-style-position: outside
這個在其他瀏覽器上都默認的樣式。不知道這個算不算IE的bug。
如何解決?
只需要將其設置爲inside的樣式(list-style-position: inside
),便可以像如下這樣:
綜上:上述的解決方案需要單獨做IE的兼容,即判斷是IE後,增加一個類,使得點在內部,並且left歸爲0。
/*IE需增加如下屬性:*/
li.isIE{
list-style-position: inside;
left: 0;
}
最終在IE上的效果爲:
2. List分欄佈局不被切斷
list要滿足Accessibility的要求,在設計的樣式爲多列時,結構依舊需要在一個<ul>
標籤內。
可以使用column-count
(IE9及以下不支持)實現多列。
如下圖,第三項被截斷了一部分放在了第二列。那問題來了,如果不想被截斷,按照最小粒度是item進行分欄怎麼辦呢?
設置如下即可:
li {
-webkit-column-break-inside: avoid;
page-break-inside: avoid;
break-inside: avoid;
}
效果如下:
demo: https://jsfiddle.net/4L8qnk5z/3/
未完待續