关于文字图片水平垂直居中

前端在项目开发过程会遇到很多的水平和垂直居中,没办法,美观。以前我的做法基本都是按套路来,文字水平居中用text-align:center 垂直居中就用line-height: 【容器高度】,如果多行文字的话就用内联元素包起来,然后再用line-height, 图片的话一般会搭配display: table;verticle-align:middle来使用。最近遇到一个强大的属性来应对一切垂直水平居中来分大家分享一下,下面直接上:

1 文字
1,设置父元素: display: flex
2,垂直居中: align-items: center
<style>
.container{
    width: 200px; 
    height: 200px;
    display: flex;
    background: #f5f5f5;
    align-items: center;
}
</style>
<body>
    <div class="container">
        今天天气很好,心情也很好!
    </div>
</body>
image.png
3,水平居中: justify-content: center,为方便看效果我把宽度加到400px, 下面看下代码及效果
<style>
.container{
    width: 400px; 
    height: 200px;
    display: flex;
    background: #f5f5f5;
    justify-content: center;
}
</style>
<body>
    <div class="container">
        今天天气很好,心情也很好!
    </div>
</body>
image.png
2 下面试试图片

为了快速看效果,这次直接加上两个属性

<style>
.container{
    width: 400px; 
    height: 400px;
    display: flex;
    background: #f5f5f5;
    justify-content: center;
    align-items: center;
}
img{
    width: 200px;
    height: 200px;
}
</style>
<body>
    <div class="container">
        <img src="./test.jpg" />
    </div>
</body>
image.png
3 试试其他块级元素呢?
<style>
.container{
    width: 400px; 
    height: 400px;
    display: flex;
    background: #f5f5f5;
    justify-content: center;
    align-items: center;
}
.content{
    width: 100px;
    height: 100px;
}
.content1{
    background: red;
}
.content2{
    background: green;
}
</style>
<body>
    <div class="container">
        <div class='content1'>今天天气好</div>
        <div class='content2'>心情也好</div>
    </div>
</body>
image.png

可以看到,块级元素被居中之后变成了内联元素,没办法设置宽高

3 有没有办法让多元素垂直排列居中呢?

答案当然是有的,用到了flex-direction: column

<style>
.container{
    width: 400px; 
    height: 400px;
    display: flex;
    background: #f5f5f5;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}
.content{
    width: 100px;
    height: 100px;
}
.content1{
    background: red;
}
.content2{
    background: green;
}
</style>
<body>
    <div class="container">
        <div class='content1'>今天天气好</div>
        <div class='content2'>心情也好</div>
    </div>
</body>
image.png

通过上面的例子相信大家已经非常清楚了,文字,图片或者多块级元素居中现在非常简单, 只需要display: flex;align-items: center; justify-content: center;三个属性就可以了。如果还想让多元素垂直排列的话,还可以加flex-direction: column属性就OK了。

最后,今天就到这里了, 如果还有特别的兴趣 可以去看看这几个属性的其他值,能让你在布局的时候有更多的思路。

需要注意的是: 如果使用了flex-direction: column,那么align-items和justify-content的效果就相反!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • H5移动端知识点总结 阅读目录 移动开发基本知识点 calc基本用法 box-sizing的理解及使用 理解dis...
    Mx勇阅读 4,619评论 0 26
  • 移动开发基本知识点 一.使用rem作为单位 html { font-size: 100px; } @media(m...
    横冲直撞666阅读 3,513评论 0 6
  • 阅读目录移动开发基本知识点 calc基本用法box-sizing的理解及使用理解display:box的布局理解f...
    张宪宇阅读 1,562评论 0 1
  • 选择qi:是表达式 标签选择器 类选择器 属性选择器 继承属性: color,font,text-align,li...
    love2013阅读 2,331评论 0 11
  • 选择qi:是表达式 标签选择器 类选择器 属性选择器 继承属性: color,font,text-align,li...
    wzhiq896阅读 1,798评论 0 2