[前端] 不定宽高居中对齐

来源:互联网 发布:json格式怎么打开mac 编辑:程序博客网 时间:2024/05/16 18:48

本篇讲下, 在不定义宽高的情况下,使内容居中对齐

HTML布局:

<div class="box">    <span>hello world !</span></div>

实现方式一

利用定位和CSS3的平移(translate)实现的

<style>.box {    position: relative;    width: 350px;    height: 160px;    background: green;}.box span {    position: absolute;    top: 50%;    left: 50%;    z-index: 2;    padding: 6px 10px;    border-radius: 3px;    background: #fff;    -webkit-transform: translate(-50%, -50%);    transform: translate(-50%, -50%);}</style>

效果:
效果一

实现方式二

利用flex属性、align-items属性和justify-content属性组合实现

flex:属性相对于同一容器其他灵活的项目,规定项目的长度
align-items:属性规定灵活容器内的各项的默认对齐方式
justify-content:在当灵活容器内的各项没有占用主轴上所有可用的空间时对齐容器内的各项(水平)。

<style>.box {    display: -webkit-flex;    display: flex;    width: 350px;    height: 160px;    background: green;    justify-content: center;  /* 水平居中 */    align-items: center; /* 垂直居中 */}.box span {    padding: 6px 10px;    border-radius: 3px;    background: #fff;}</style>

效果同上,这里加了一个br换行效果

效果二

实现效果三(不建议)

就是用js来动态实现

css样式

<style>.box {    position: relative;    width: 350px;    height: 160px;    background: green;}.box span {    position: absolute;    top: 50%;    left: 50%;    z-index: 2;    padding: 6px 10px;    border-radius: 3px;    background: #fff;}</style>

js脚本

<script>$('.box span').css({    marginTop: -$('.box span').outerHeight()/2,    marginLeft: -$('.box span').outerWidth()/2});</script>

实现效果4

<style>.box {    width:350px;    height:100px;    border:1px solid black;    /* Internet Explorer 10 */    display:-ms-flexbox;    -ms-flex-pack:center;    -ms-flex-align:center;    /* Firefox */    display:-moz-box;    -moz-box-pack:center;    -moz-box-align:center;    /* Safari, Chrome, and Opera */    display:-webkit-box;    -webkit-box-pack:center;    -webkit-box-align:center;    /* W3C */    display:box;    box-pack:center;    box-align:center;}</style>

值得讲下的是box-pack 设置子元素的垂直对齐方式(这个子元素要小于父元素)

HTML布局:

<div class="box">    <a href="javascript:;">天涯何处无芳草,<br/>TMD就是找一到</a></div>

效果:
效果四

附加:
1、如果只有一行文本的话,也可以使用line-height和text-align来实现,缺点是多行就不行了

先写到这里,如果看客有更好的方法,不防留言告诉小生,不生感激,谢谢关注~

0 0
原创粉丝点击