1. 自适应内部元素的宽度max-width: min-content;
如果不给元素指定一个具体的 height,它就会自动适应其内容的高度。尝试对width 也实现类似的行为。
使 figure 元素能跟它所包含的图片一样宽(图片的尺寸往往不是固定的),而且是水平居中的。
- 让
<figure>
元素浮动会让它得到正确的宽度,但同时也彻底改变了它的布局模式 - 对 figure 应用 display: inline-block 会让它根据内容来决定自身的尺寸,但很难继续完成水平居中
- 对 fifigure 应用一个固定的 width 或max-width ,然后对 figure > img 应用 max-width: 100%。可是这个方法无法实现响应式
width 和 height 属性有一个新的关键字 min-content
。这个关键字将解析为这个容器内部最大的不可断行元素的宽度(即最宽的单词、图片或具有固定宽度的盒元素)。
figure {width: min-content;margin: auto;
}
<!DOCTYPE html>
<html><head><style> figure {/*回退机制*//* max-width: 300px;*//*把 figure 设置为恰当的宽度,并让它水平居中*/max-width: min-content;margin: auto;}figure > img {max-width: inherit;}/* Basic styling */figure {padding: 10px;border: 1px solid silver;} </style></head><body><p>Let’s assume we have some text here. Bacon ipsum dolor sit amet turkeyveniam shankle, culpa short ribs kevin t-bone occaecat.</p><figure><img src="http://csssecrets.io/images/adamcatlace.jpg" /><figcaption>The great Sir Adam Catlace was named after Countess Ada Lovelace, thefirst programmer ever.</figcaption></figure><p>We also have some more text here. Et laborum venison nostrud, ut veniamsint kielbasa ullamco pancetta.</p></body>
</html>
2. 精确控制表格列宽——table-layout: fixed
table-layout
的默认值是 auto,其行为模式是我们最为熟悉的表格布局行为
对表格应用 table-layout: fixed
之后的效果。按从上到下的顺序总结为:
- 如果不指定任何宽度,则各列的宽度将是平均分配的;
- 后续的表格行并不会影响列宽;
- 给单元格指定很大的宽度也会直接生效,并不会自动缩小;
- overflow 和 text-overflow属性都是可以正常生效的;
- 如果overflow 的值是 visible,则单元格的内容有可能会溢出
对 <table>
元素或其他具有 display: table 样式的元素应用table-layout: fixed
属性
请注意,为了确保
table-layout: fixed
奏效,需要为这些表格元素指定一个宽度(哪怕是 100%)。同样,为了让 text-overflow:ellipsis 发挥作用,还需要为那一列指定宽度
<!DOCTYPE html>
<html><head><style> body {background: #ddd;}section {width: 500px;margin: 2em;background: white;}table {border-collapse: collapse;margin-bottom: 1em;width: 100%;}section + section table {table-layout: fixed;}td {border: 1px solid #aaa;}td.preformatted {white-space: pre;font-family: Consolas, Monaco, monospace;text-overflow: ellipsis;overflow: hidden;} </style></head><body><section><h1>With table-layout: auto</h1><div><table><tr><td>If we don’t…</td><td>specify a cell width, they will be assigned one that depends ontheir contents. Notice how the cell with the more content here ismuch wider.</td></tr></table><table><tr><td>If we don’t…</td><td>specify a cell width, they will be assigned one that depends ontheir contents. Notice how the cell with the more content here ismuch wider.</td></tr><tr><td>All rows take part in calculating the widths, not just the firstone.</td><td>Notice how the dimensions here are different than the previousexample.</td></tr></table><table><tr><td style="width: 1000px">If we specify a width, it will not always be followed. I have awidth of <code>1000px</code>…</td><td style="width: 2000px&