5

前端开发常见布局

 2 years ago
source link: https://segmentfault.com/a/1190000040841889
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

前端开发在页面搭建初期,往往需要我们具备框架性的思维,根据设计图来划分页面板块结构,以及在不同尺寸设备间的差异处理。掌握一些常见的布局,可以使我们事半功倍,本文就来聊一聊居中布局。

文字居中对齐

标题所说的居中对齐是指一个div内的文字在其水平和垂直方向都处于中心的位置。假设有下面DOM结构:

<div class="wrap">
 <span>对齐方式:水平垂直居中</span> 
</div>

样式代码如下:

.wrap {
    height: 100px;
    border: 2px solid blueviolet;
}

在浏览器中渲染出来大概是下面的样子:

我们通过css样式来分步骤达到居中对齐的效果

文字水平居中

这个是很基础的前端知识,只需要给样式中加上text-align: center

.wrap {
    height: 100px;
    border: 2px solid blueviolet;
    text-align: center;
}

浏览器结果:
1

文字垂直居中

现在需求又要变更,需要文字在容器中垂直方向也要居中,怎么办?使用margin或者padding?还是使用定位?恐怕都不够优秀。其实只要在加一行样式即可 line-height: 100px

.wrap {
    height: 100px;
    border: 2px solid blueviolet;
    text-align: center;
    line-height: 100px;
}

浏览器结果:
1
可见只要设置一个容器的line-height和height一样大时,它内部的文字就可以垂直居中,这个属性也适用于a标签等其他标签,在写按钮的样式需要按钮文字居中时很有用。

块元素居中对齐

考虑有下面的DOM结构

<div class="parent02">
    <div class="child01">块元素:垂直居中对齐</div>
</div>

样式代码如下,浏览器效果如图

.parent02 {
    height: 100px;
    border: 2px solid rgba(13,202,240,.8);
}
.child01 {
    background-color: rgb(48, 245, 245);
    width: 80%;
    height: 50%;
}

block

水平居中对齐

只要给.child01 中添加一行 margin: 0 auto即可水平居中

.child01 {
    background-color: rgb(48, 245, 245);
    width: 80%;
    height: 50%;
    margin: 0 auto;
}

block

垂直居中对齐

细心的小伙伴可能注意到上边.child01的高度设置为父级的50%,我们可以设置它的margin-top或者parent02的padding-top来达到垂直居中的目的,但是如果.parent02和.child01的高度都不确定呢?恐怕就需要不停的修改样式了。这时flex布局就可以帮了,只需要在父级中设置即可,加入下边两行,无论.parent02和.child01的高度怎么变化都可以保持居中

.parent02 {
    height: 100px;
    border: 2px solid rgba(13,202,240,.8);
    display: flex;
    align-items: center;
}

block

大功告成!到这里本文要说的居中布局就要告一段落了,我们来回顾一下主要关键点

  • 文字居中使用 text-align 和 line-height
  • 块元素居中使用 margin:0 auto 和 flex

希望本文对你能有帮助^_^

原文连接🔗


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK