我爱编程

CSS的几种布局方式

2018-04-09  本文已影响0人  b9973d078544

一.左右布局

1.使用float:left,父元素添加clearfix,且左右盒子宽之中不能大于父盒子大小。

2.使用position: absolute;父元素添加 position: relative;

3.使用宽度百分比


二.左中右布局

1.左中使用float:left,右使用float:right,父元素添加clearfix,且左中右盒子宽度之和不能大于父盒子大小。

2.使用position: absolute;父元素添加    position: relative;

3.使用宽度百分比


三.水平居中

1.内联元素

在块级父元素中水平居中内联元素

例:

<nav><a href="#">ABC</a><nav>

nav {text-aligin:center;}


2.块级元素

块级元素设置margin-left与margin-right为atuo(要有固定宽)

例:

<div>ABCD<div>

div{

width:200px;

margin:0 atuo;

}


3.大于一个块级元素

当要使两个以上的块级元素居中时可以使用inline-block或flexbox

inline-block:

<div class="main">

    <div class="inline-blcok-center">ABCD</div>

    <div class="inline-blcok-center">ABCD</div>

</div>

main{

text-algin:center

}

.inline-block-center{

display:inline-block;

text-algin:left;

}


flex:

<div class="main">

   <div class="flex-center">ABCD</div>

   <div class="flex-center">ABCD</div>

</div>

.flex-center{

display:flex;

justify-content:center;

}


四.垂直居中

1.内联元素

1.1单行内联元素

1.1.1使其上下padding相等

例:

<main>

<a href="#">ABCD</a>

<a href="#">ABCD</a>

<a href="#">ABCD</a>

</main>

a {

padding-top:40px;

padding-bottom:40px;

}


1.1.2 让line-height与height相等

<div>ABCD<div>

div{

height:100px;

line-height:100px;

}

1.2多行内联元素

使用表格:

<table><tr><td>ABCD</td></tr></table>

<div class="center-table"><p>ABCD</p></div>

table{

border-collapse:separate;

}

.center-table {

display:table;

}

.center-table p{

display:table-cell;

margin:0;

vertical-align:middle;


使用flexbox(要有固定高度)

例:

<div class="flex-center">

<p>ABCD</p>

<div>

.flex-center{

display:flex;

fex-direction:column;

justify-content:center;

hegiht:200px;

resize:vertical;

overflow:auto;

}


2.块状元素

2.1. 已知高度:

使用相对定位:

例:

.div{

position:relative;

}

.div child {

position:absolute;

top:50%;

height:100px;

margin-top:-50px;

}


2.2高度未知

例:

.div{

position:relative;

}.

.child{

position:absolute;

top:50%;

transform:translateY(-50%);

}


2.3 使用flexbox

例:

.parent{

display:flex;

flex-direction:column;

justify-content:center;

}

五.水平垂直居中

1.固定宽高

使用负边距等于高/宽的一半,再使用定位

例:

.parent{

position:relative;

}

.child{

width:300px;

height:100px;

padding:20px;

position:absolute;

top:50%;

left:50%;

margin:-70px00-170px;

}


2.不知道固定宽高

使用transform,负方向-50%,使其到中心

例:

.parent{

position:relative;

}

.child{

position:absolute;

top:50%;

left:50%;

transform:translate(-50%, -50%);

}


六.dispaly:inline-block的bug

span{

display:inline-block;

vertical-align: top;

}

上一篇 下一篇

猜你喜欢

热点阅读