行内子元素的垂直水平居中
方法一
通过在父元素中设置text-align: center;
,让子元素水平居中,然后通过line-height
属性让子元素进行垂直居中。
<style>
#parent{
background-color: #000;
height: 400px;
text-align: center;
line-height: 400px;
}
#son{
background-color: #fff;
}
</style>
<body>
<div id="parent">
<span id="son">test</span>
</div>
</body>
缺点:父元素需要设置高度height
。
块级子元素的垂直水平居中
方法一(常用)
父元素设置相对定位position: relative;
,子元素通过postition:absolute;
进行绝对定位,然后用百分比设置top
和left
,再用margin-left
和margin-top
消除子元素宽高的一半偏移量。
<style>
html{
height: 100%;
}
body{
height: 100%;
margin: 0;
}
#parent{
background-color: #000;
position: relative;
height: 100%;
}
#son{
background-color: #fff;
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px; /*高度的一半*/
margin-left: -50px; /*宽度的一半*/
}
</style>
<body>
<div id="parent">
<div id="son"></div>
</div>
</body>
缺点:需要获取子元素的宽高。
方法二
可以使用 CSS3 的 transform
代替 margin
:
transform
中 translate
偏移的百分比是相对于自身大小的。
<style>
html{
height: 100%;
}
body{
height: 100%;
margin: 0;
}
#parent{
background-color: #000;
position: relative;
height: 100%;
}
#son{
background-color: #fff;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<body>
<div id="parent">
<div id="son">test</div>
</div>
</body>
缺点:兼容性差。
方法三
父元素设置相对定位position: relative;
,子元素通过postition:absolute;
进行绝对定位,然后将top
、right
、bottom
和left
设为0
,再设置magin
为auto
。
<style>
html{
height: 100%;
}
body{
height: 100%;
margin: 0;
}
#parent{
background-color: #000;
position: relative;
height: 100%;
}
#son{
width: 100px;
height: 100px;
background-color: #fff;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
</style>
<body>
<div id="parent">
<div id="son"></div>
</div>
</body>
缺点:子元素需要设置宽高。
方法四
子元素设置相对定位position: relative;
,然后使用margin: 0 auto;
实现水平居中,然后用百分比设置top
,使用margin-top
或者transform: translateY(-50%);
消除子元素的一半偏移量实现垂直居中。
<style>
html{
height: 100%;
}
body{
height: 100%;
margin: 0;
}
#parent{
background-color: #000;
height: 100%;
overflow: hidden; /*防止边距重叠*/
}
#son{
width: 100px;
height: 100px;
background-color: #ccc;
margin: 0 auto;
position: relative;
top: 50%;
/* transform: translateY(-50%);*/ /*可以这样消除子元素的一半偏移量 */
margin-top: -50px; /*也可以这样*/
}
</style>
<body>
<div id="parent">
<div id="son"></div>
</div>
</body>
缺点:子元素需要设置宽高,否则margin: 0 auto;
起不了居中作用。
方法五
父元素使用弹性布局display: flex;
,然后通过设置属性align-items: center;
和justify-content: center;
实现子元素的垂直水平居中。
<style>
html{
height: 100%;
}
body{
height: 100%;
margin: 0;
}
#parent{
background-color: #000;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
#son{
background-color: #fff;
}
</style>
<body>
<div id="parent">
<div id="son">test</div>
</div>
</body>
缺点:兼容性差。
方法六
父元素使用弹性布局display: flex;
,然后子元素设置属性margin: auto;
实现垂直水平居中。
<style>
html{
height: 100%;
}
body{
height: 100%;
margin: 0;
}
#parent{
background-color: #000;
height: 100%;
display: flex;
}
#son{
background-color: #fff;
margin: auto;
}
</style>
<body>
<div id="parent">
<div id="son">test</div>
</div>
</body>
缺点:兼容性差。