css水平垂直居中

笑着哭i 提交于 2020-03-04 09:30:45

1.元素水平居中:元素是行内块元素,可以设置宽度的情况下,margin: 0 auto;

2.一个已知宽度和高度的开启了position: absolute;的元素(父元素开启position: relative;)

<div class="wrap">    <div class="content"></div></div>
<style>    .wrap { background-color: red;  width: 300px;  height: 300px;  position: relative;  }    .content { background-color: yellow;  width: 100px;  height: 100px;  position: absolute;  left: 50%;  top: 50%;  margin: -50px 0 0 -50px;  }</style>

3.一个宽高不固定的元素,同上方式,把固定可知的margin替换成 transform: translate(-50%, -50%);

<div class="wrap">    <div class="content">11111</div></div>
<style>    .wrap { background-color: red;  width: 300px;  height: 300px;  position: relative;  }    .content { background-color: yellow; position: absolute;  left: 50%;  top: 50%;  transform: translate(-50%, -50%); }</style>

4.flex弹性布局

<div class="wrap">    <div class="content"> 11111 </div></div>
<style>    .wrap { display: flex; justify-content: center; align-items: center; width: 300px;  height: 300px;background: red;}    .content { background-color: yellow; }</style>

5. table布局

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!