因爲p標籤和img居中的方法 我知道的不多 就放到一起了!
1.單行文字的居中很簡單 一個text-align:center; line-hegight: 父級div的高度。就OK!
2.關鍵是多行!當然如果父級高度不定,我們可以文字的標籤加個padding 也可以解決,但這不是一個好的方案。
下面父級div固定高度 居中的寫法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container{
width: 400px;
height: 400px;
border: 1px solid red;
text-align: center;
display: table-cell;
vertical-align: middle;
}
span{
display: inline-block;
width: 200px;
}
</style>
</head>
<body>
<div class="container">
<span>我是多行文字,我是多行文字,我是多行文字,我是多行文字我會居中!</span>
</div>
</body>
</html>
3.原理很簡單,就是利用table-cell下面的 vertical-align。
以上是文字居中的方法。
-------------------------------------------------------------------------圖片居中--------------------------------------------------------------------------------------
1.與文字居中一樣。同樣使用的是vertical-align.代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container{
width: 400px;
height: 400px;
border: 1px solid red;
text-align: center;
display: table-cell;
vertical-align: middle;
}
img{
display: inline-block;
width: 200px;
}
</style>
</head>
<body>
<div class="container">
<img src="1.jpg" alt="">
</div>
</body>
</html>
2.將最外層div設置成table 包裹img的div改成table-cell;全部加上 vertical-align:middle;即可!代碼如下。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>圖片居中</title>
<style>
.box{
display: table;
float: left;
margin: 0 10px;
width: 180px;
height: 180px;
border: 1px solid #333;
text-align: center;
vertical-align: middle;
}
.innerBox{
display: table-cell;
vertical-align: middle;
}
img{
width: 90%;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="box">
<div class="innerBox">
<img src="2.jpg" alt="">
</div>
</div>
</body>
</html>
3.用背景圖片做!利用background-position中有個center屬性。可以完美實現居中。當然,別忘了background-repeat: no-repeat;
background-image: url();路徑要寫在行間
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>圖片居中</title>
<style>
.box{
display: table;
float: left;
margin: 0 10px;
width: 200px;
height: 200px;
border: 1px solid #333;
background-repeat: no-repeat;
background-position: center;
}
</style>
</head>
<body>
<div class="box" style="background-image: url(1.jpg);">
</div>
</body>
</html>