如何使用 CSS 将图像并排对齐?
要将图像并排对齐,我们可以在 CSS 中使用float属性。此外,flex 也允许我们对齐图像。让我们通过示例逐一了解它们,首先从使用 float 属性将图像并排对齐开始。
使用 Float 将图像并排对齐
我们可以使用 CSS 的 float 属性将图像等元素浮动到包含父元素的左侧或右侧。其他元素会围绕浮动内容放置。具有相同 float 属性值的多个元素都会并排放置。
在这个示例中,图像使用 float 属性的值 left 放置在左侧。由于所有图像都设置了 float: left,因此它们会并排排列:
.imageColumn {
float: left;
width: 25%;
padding: 10px;
}
.imageColumn 是我们要并排对齐的所有图像的 div:
<div class="imageColumn"> <img src="https://tutorialspoint.com/images/clipart/flow/flow4.jpg" alt="Leaf" style="width:100%"> </div>
示例
以下是使用 float 将图像并排对齐的代码:
<!DOCTYPE html>
<html>
<head>
<style>
* {
box-sizing: border-box;
}
.imageColumn {
float: left;
width: 25%;
padding: 10px;
}
h1{
text-align: center;
}
</style>
</head>
<body>
<h1>Images Aligned Side by Side example</h1>
<div>
<div class="imageColumn">
<img src="https://tutorialspoint.com/images/clipart/flow/flow4.jpg" alt="Leaf" style="width:100%">
</div>
<div class="imageColumn">
<img src="https://tutorialspoint.com/images/clipart/cartoon/cartoon2.jpg" alt="Cartoon" style="width:100%">
</div>
<div class="imageColumn">
<img src="https://tutorialspoint.com/images/clipart/animal/animal9.jpg" alt="Animal" style="width:100%">
</div>
<div class="imageColumn">
<img src="https://tutorialspoint.com/images/clipart/sport/sport11.jpg" alt="Sports" style="width:100%">
</div>
</div>
</body>
</html>
使用 Flex 将图像并排对齐
要将图像并排对齐,请在 CSS 中使用display属性并将其设置为flex。对齐方式使用justify-content属性和值center设置:
div {
display: flex;
justify-content: center;
}
示例
让我们来看一个使用 flex 将图像并排对齐的示例:
<!DOCTYPE html>
<html>
<head>
<style>
div {
display: flex;
justify-content: center;
}
img {
margin: 10px 20px;
}
</style>
</head>
<body>
<h1>Align Images</h1>
<div>
<img src="https://tutorialspoint.com/jsf/images/jsf-mini-logo.jpg" />
<img src="https://tutorialspoint.com/cprogramming/images/c-mini-logo.jpg" />
<img src="https://tutorialspoint.com/cplusplus/images/cpp-mini-logo.jpg" />
</div>
</body>
</html>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP