CSS 中的右很多对齐的方式,今天主要来分享 20 个常用的对齐方式。
来一起看看吧。
1.1 水平居中对齐块元素
- .box {
- width: 1180px;
- height: 100px;
- border: 1px solid #0f0;
- margin: 10px auto;
- }
-
比如,tb的这个顶部导航和中间内容区块,都是居中的:
1.2 水平居中对齐图像
- img {
- display: block;
- width: 50%;
- margin: 10px auto;
- }
-
1.3 水平居中对齐文本
- .box {
- width: 600px;
- height: 100px;
- text-align: center;
- border: 1px solid #333;
- }
-
2.1 垂直居中对齐块元素
- .box {
- width: 400px;
- height: 100px;
- background: #0f0;
- padding: 20px 0px;
- }
-
比如,wyy右侧这块,上下都居中,可以用 padding 或者相同的 margin,都能实现。
2.2 垂直居中对齐文本
- .box {
- width: 400px;
- height: 100px;
- background: #0f0;
- line-height: 100px;
- }
-
比如,wyy音乐导航这里,文字就是垂直居中。
2.3 垂直居中对齐元素之flexbox(CSS3)
- .box {
- width: 400px;
- height: 100px;
- background: #0f0;
- display: flex;
- align-items: center;
- }
-
3.2 使用 padding
- .box {
- padding: 20px;
- }
-
3.2 使用 position 和 transform
- .box {
- width: 400px;
- height: 100px;
- background: #0f0;
- position: absolute;
- left: 50%;
- top: 50%;
- transform: translate(-50%, -50%);
- }
-
比如dy的登录弹窗。
3.3 使用 flexbox
- .box {
- width: 400px;
- height: 100px;
- background: #0f0;
- display: flex;
- justify-content: center;
- align-items: center;
- }
-
4.1 float 左对齐
- .box {
- width: 400px;
- background: #0f0;
- float: left;
- }
-
注意:使用时候,记得给父级增加 clearfix,防止浮动导致父级高度塌陷。
- /* 清除浮动样式 */
- .clearfix::after {
- content: '';
- display: table;
- clear: both;
- }
-
4.2 float 右对齐
- .box {
- width: 400px;
- background: #0f0;
- float: right;
- }
-
注意:使用时候,记得给父级增加 clearfix,防止浮动导致父级高度塌陷。
- /* 清除浮动样式 */
- .clearfix::after {
- content: '';
- display: table;
- clear: both;
- }
-
4.3 让文本居左
- .box {
- text-align: left;
- }
-
4.4 让文本居右
- .box {
- text-align: right;
- }
-
4.5 使用定位让元素居左
- .box {
- width: 400px;
- background: pink;
- position: absolute;
- left: 0;
- }
-
4.6 使用定位让元素居右
- .box {
- width: 400px;
- background: #00f;
- position: absolute;
- right: 10px;
- }
-
比如,tb右侧客服这块。
5.1 两端对齐多个元素之 float
- .box-left {
- width: 800px;
- background: #00f;
- float: left;
- }
- .box-right {
- width: 300px;
- background: #0f0;
- float: right;
- }
-
注意:使用时候,记得给父级增加 clearfix,防止浮动导致父级高度塌陷。
- /* 清除浮动样式 */
- .clearfix::after {
- content: '';
- display: table;
- clear: both;
- }
-
比如,淘宝这块。
5.2 两端对齐多个元素之 flexbox(CSS3)
- .box {
- width: 400px;
- background: #0f0;
- display: flex;
- justify-content: space-between;
- }
-
5.3 两端对齐文本
- .box {
- width: 400px;
- background: #0f0;
- text-align: justify;
- }
-
6.1 底部对齐元素
- .box {
- width: 400px;
- height: 400px;
- background: #0f0;
- display: flex;
- align-items: flex-end;
- justify-content: flex-start;
- }
-
7.1 顶部对齐元素
- .box {
- width: 400px;
- height: 400px;
- background: #0f0;
- display: flex;
- align-items: flex-start; /* 不让子元素拉伸至整个父级高度 */
- justify-content: flex-start; /* 水平顶端对齐 */
- }
-
OK,本文完。