HTML+CSS 内容居中效果

,1.水平居中

  a).如果被设置元素为文本、图片等行内元素时,水平居中是通过给父元素设置  text-align:center来实现的。当被设置元素为块状元素时用 text-align:center 并达不到居中的效果。分为定宽块状元素和不定宽块状元素两种情况。

      b).定宽块状元素,对其板块本身进行设置:width:500px;   margin:20px auto;

       

2.垂直居中

  a).父元素高度确定的单行文本的竖直居中的方法是通过设置父元素的 height 和 line-height 高度一致来实现的。

       b).父元素高度确定的多行文本、图片、块状元素的竖直居中的方法有两种:使用插入 table (包括tbody、tr、td)标签,同时设置vertical-align:middle

 

3.margin: auto 居中

div.center background: hsl(60, 100%, 97%)}

div.center img display: blockwidth: 33%height: automargin: 0 auto}

 

4.table-cell 居中

 可以实现水平垂直都居中。通常需要添加一个额外的空元素。

<div class="center-aligned">
<div class="center-core">
<img src="jimmy-choo-shoe.jpg">
</div>
</div>

 

5.Absolute 居中

.absolute-aligned {
position: relativemin-height: 500px;
background: hsl(200, 100%, 97%);
}
.absolute-aligned img {
width: 50%;
min-width: 200px;
height: auto;
overflow: automargin: auto;
position: absolute;
top: 0left: 0bottom: 0right: 0;
}

6.使用 translate 居中

.center background: hsl(180, 100%, 97%)position: relativemin-height: 500px}
.center img position: absolutetop: 50%left: 50%;
transform: translate(-50%, -50%)width: 30%height: auto}


7.使用 Flexbox 居中

.center background: hsl(240, 100%, 97%);
display: -webkit-box/* OLD: Safari, iOS 6 and earlier; Android browser, older WebKit */
display: -moz-box/* OLD: Firefox (can be buggy) */
display: -ms-flexbox/* OLD: IE 10 */
display: -webkit-flex/* FINAL, PREFIXED, Chrome 21+ */
display: flex/* FINAL: Opera 12.1+, Firefox 22+ */
-webkit-box-align: center;
-moz-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
-webkit-box-pack: center;
-moz-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
}

8.使用 calc 居中

.center img width: 40%height: autoposition: absolute;
top: -webkit-calc(50% - 20%)left: -webkit-calc(50% - 20%);
top: -moz-calc(50% - 20%)left: -moz-calc(50% - 20%);
top: calc(50% - 20%)left: calc(50% - 20%)}
 
 
9.单行文本垂直居中,demo

html

div id="parent"> <div id="child">Text here</div> </div>

css
#child {
line-height: 200px;
}
10.垂直居中一张图片
 
html
<div id="parent">
<img src="image.png" alt="" />
</div>
 

 

css

#parent {
line-height: 200px;
}
#parent img {
vertical-align: middle;
}


posted @ 2017-06-22 20:10  YUANRONGRONG  阅读(483)  评论(0编辑  收藏  举报