CSS居中各种情况的解决情况

2017-10-03  本文已影响0人  就想叫菜鸟

CSS居中的几种情况

1. 元素水平居中

//html代码:
<div id="center"></div>

//css代码:
#center {
    height: 200px;
    width: 200px;
    background: #222;
    margin: 0 auto;
}
//html代码:
<div id="center">
    <p>关于函数声明,它的重要特征就是函数声明提升,意思是在执行代码之前会先读取函数声明。
    </p>
</div>

//css代码:
#center {
    height: 200px;
    width: 200px;
    background: #222;
    margin: auto;
}
p{
    color: white;
    width: 60%;
    margin: auto;
}
//html代码:
<div class="container">
    <div class="box"></div>
</div>

//css代码:
.container {
    width: 300px;
    height: 300px;
    background: #eee;
    position: relative;
    margin: 10px auto;
}

.box {
    width: 100px;
    height: 100px;
    background: #222;
    position: absolute;
    /*计算left的值: (300-100)/2;*/
    left: 100px;
}
.container {
    width: 400px;
    height: 400px;
    background: #eee;
    position: absolute;
    left: 0;
    bottom: 0;
    top: 0;
    right: 0;
    margin: 0 auto;
}
//html代码:
<div class="container">
    <div class="box"></div>
</div>

//css代码:
.container {
    width: 70%;
    height: 300px;
    background: #eee;
    position: relative;
    margin: 10px auto;
}

.box {
    width: 100px;
    height: 100px;
    background: #222;
    position: absolute;
    left: 50%;
    margin-left: -50px;
    /*transform: translateX(-50%)*/;
    //向左移动自身宽度的一半
}
//html代码:
<div class="container">
    <div class="box"></div>
</div>

//css代码
.container {
    width: 70%;
    height: 300px;
    background: #eee;
    position: relative;
    margin: 10px auto;
}

.box {
    width: 70%;
    height: 100px;
    background: #222;
    position: absolute;
    left: 50%;
    margin-left: -35%;
    /*transform: translateX(-50%)*/;
}

2. 元素垂直居中

//html代码:
<div class="container">
    <h1>some headline</h1>
</div>

//css代码:
.container {
    width: 400px;
    height: 400px;
    background: #eee;
    margin: 50px auto;
}

h1 {
    text-align: center;
    /*简写*/
    /*font: 40px/400px Helvetica, sans-serif;*/
    font-size: 40px;
    line-height: 400px;
}
//html代码:
<div class="container"></div>

//css代码:
.container {
    width: 400px;
    height: 400px;
    background: #eee;
    margin: 0 auto;
    position: relative;
    top: 50%;
    margin-top: -200px;
}
html, body {
    height: 100%;
}
//这里一定要设置body, html的高度。
.container {
    width: 400px;
    height: 30%;
    background: #eee;
    margin: 0 auto;
    position: relative;
    top: 50%;
    transform: translateY(-50%); 
}
html, body {
    height: 100%;
}
.container {
    width: 400px;
    height: 400px;
    background: #eee;
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); 
}
html, body {
    height: 100%;
}

3. 背景图片居中

.container {
  height: 300px;
  width: 300px;
  margin: 150px auto;
  background: #eee url(http://lorempixum.com/100/100/nature/4)     no-repeat center;
  /*background-bottom有九种属性,上面的center即为background-position属性*/
}
上一篇 下一篇

猜你喜欢

热点阅读