例如,您想在文本旁边显示图像,通常我会这样做:
<table>
<tr>
<td><img ...></td>
<td>text</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
还有更好的选择吗?
Nei*_*gan 19
您应该将它们浮动到已清除的容器中.
例:
https://jsfiddle.net/W74Z8/504/
一个干净的实现是"clearfix hack".这是Nicolas Gallagher的版本:
/**
* For modern browsers
* 1. The space content is one way to avoid an Opera bug when the
* contenteditable attribute is included anywhere else in the document.
* Otherwise it causes space to appear at the top and bottom of elements
* that are clearfixed.
* 2. The use of `table` rather than `block` is only necessary if using
* `:before` to contain the top-margins of child elements.
*/
.clearfix:before,
.clearfix:after {
content: " "; /* 1 */
display: table; /* 2 */
}
.clearfix:after {
clear: both;
}
/**
* For IE 6/7 only
* Include this rule to trigger hasLayout and contain floats.
*/
.clearfix {
*zoom: 1;
}
?
Run Code Online (Sandbox Code Playgroud)
小智 7
是的,div和CSS通常是放置HTML的更好,更简单的方法.有很多不同的方法可以做到这一点,这完全取决于上下文.
例如,如果要将图像放在文本的右侧,可以这样做:
<p style="width: 500px;">
<img src="image.png" style="float: right;" />
This is some text
</p>
Run Code Online (Sandbox Code Playgroud)
如果你想并排显示多个项目,通常也会选择float.例如:
<div>
<img src="image1.png" style="float: left;" />
<img src="image2.png" style="float: left;" />
<img src="image3.png" style="float: left;" />
</div>
Run Code Online (Sandbox Code Playgroud)
只要你有水平空间,将这些图像浮动到同一侧就会彼此相邻.
所有这些问题的答案可以追溯到2016年或更早的...有这个使用新的网络标准flex-boxes
。总的来说floats
,这些问题现在是不受欢迎的。
HTML
<div class="image-txt-container">
<img src="https://images4.alphacoders.com/206/thumb-350-20658.jpg">
<h2>
Text here
</h2>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS
.image-txt-container {
display: flex;
align-items: center;
flex-direction: row;
}
Run Code Online (Sandbox Code Playgroud)
小提琴示例:https : //jsfiddle.net/r8zgokeb/1/