Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CSS水平居中 #4

Open
liangfengbo opened this issue Aug 1, 2019 · 0 comments

Comments

@liangfengbo
Copy link
Owner

commented Aug 1, 2019

水平居中

<ul class="parent">
    <li class="child">水平居中</li>
</ul>

水平居中方法一

  • 在父元素设置 text-align: center;
  • 把子元素设置为 display: inline-block;
  • 优点:兼容性好,ie6都支持
  • 缺点:child里面的文字也会居中,需要设置 text-align: left; 还原
.parent {
    text-align: center;
}

.child {
    display: inline-block;
}

水平居中方法二

  • 把子元素设置为 display: table;,再设置 margin: 0 auto;
  • 优点:简单,只需要设置子元素就好
  • 缺点:ie6和ie7不支持 display 转换为 table
.parent {
}

.child {
    display: table;
    margin: 0 auto;
}

水平居中方法三

  • 父元素设置为相对定位
  • 子元素设置为绝对定位,left值设置为50%,再使用 transform 左移50%
  • 优点:子元素绝对定位,不会对其他元素造成影响
  • 缺点:transform为css3内容,存在一定低浏览器的兼容性问题
.parent {
    position: relative;
}

.child {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}

水平居中方法四

  • 父元素设置弹性盒子,子元素设置 margin: 0 auto;
  • 优点:简单快捷
  • 缺点:flex存在一定的低版本浏览器兼容性问题
.parent {
    display: flex;
}

.child {
    margin: 0 auto;
}

水平居中方法五

  • 设置父元素为弹性盒子,再设置内容对齐 justify-content: center;
  • 优点:简单快捷
  • 缺点:flex存在一定的低版本浏览器兼容性问题
.parent {
    display: flex;
    justify-content: center;
}

.child {
}

水平居中方法六

  • 设置父元素为网格,子元素再设置为justify-self: center;
.parent {
    display: grid;
}
.child {
    justify-self: center;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
1 participant
You can’t perform that action at this time.