CSS可以像表格一样显示右对齐、居中对齐和左对齐的图像



我想使用CSS来重现下面简单HTML表的行为。

HTML表的宽度为100%,只有一行三列。每列包含一个图像,其中图像1左对齐;图像2居中;并且图像3是右对齐的。

重要的是,当浏览器窗口的大小调整为非常小时,图像不应重叠或换行到下一行。它们应该只是在同一行中挨着(这就是表解决方案的作用)。

这听起来是一个很简单的要求,但我已经为此挣扎了很多小时,所以任何帮助都将不胜感激。

<html>
<head>
<title>Test</title>
</head>
<body>
<table width="100%">
<tr>
<td align="left">
<img width="150" height="129" src="image1.gif">
</td>
<td align="center">
<img width="400" height="120" border="0" src="image2.jpg"> <!-- This is the main logo  -->
</td>
<td align="right">
<img width="141" height="80" src="image3.png">
</td>
</tr>
</table>
</body>
</html>

您可以使用display: tabledisplay: table-cell来获得表的类似属性。

html

<div class="table">
    <div class="table-cell center">
        <p>Center</p>
    </div>
    <div class="table-cell left">
        <p>Left</p>
    </div>
    <div class="table-cell right">
        <p>Right</p>
    </div>
</div>

css

.table{
  display: table;
}
.table-cell{
  height: 100px;
  width: 100px;
  display: table-cell;
  vertical-align: middle;
}
.center{text-align: center;}
.left{text-align: left;}
.right{text-align: right;}

看看这支钢笔:http://codepen.io/codefancy/pen/PqQjyb/

我终于想出了一个相当混乱的解决方案。它使用条件注释为InternetExplorer(版本5以上)提供解决方案。以下代码通过W3C标记和css验证。该解决方案可以扩展为在不使用表的情况下生成流体3列布局的"圣杯"。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-GB" lang="en-GB">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Test</title>
<style type="text/css">
.table{
  display: table;
  width: 100%;
}
.table-cell{
  height: 100px;
  width: 100px;
  display: table-cell;
  vertical-align: middle;
}
.center{text-align: center;}
.left{text-align: left;}
.right{text-align: right;}
</style>
<!--[If IE]>
<style type="text/css">
.table{
  display: none;
}
.table-cell{
  display: none;
}
</style>
<![endif]-->

</head>
<body>
<div class="table"><div class="table-cell left">
<!--[If IE]></div></div><table width="100%"><tr><td class="left"><![endif]-->
<img width="150" height="129" alt="star" src="image1.gif" />
<!--[If IE]><div><![endif]-->
</div><div class="table-cell center">
<!--[If IE]></div></td><td class="center"><![endif]-->
<img width="400" height="120" alt="logo" src="image2.jpg" /> <!-- This is the main logo  -->
<!--[If IE]><div><![endif]-->
</div><div class="table-cell right">
<!--[If IE]></div></td><td class="right"><![endif]-->
<img width="141" height="80"  alt="thumbs up" src="image3.png" />
<!--[If IE]><div><div><![endif]-->
</div></div>
<!--[If IE]></td></tr></table><![endif]-->
</body>
</html>

谢谢你的帮助,我一直在寻找这样的解决方案很长时间了。

最新更新