CSS居中问题整理
给出基本布置代码及效果图
HTML:
<body>
<div id="gfather">
<div id="father">
<div class="child">
<span>test 文本</span>
</div>
</div>
<div>
HAHAHAHA
</div>
</div>
<div>
hahahaha
</div>
</body>
CSS:
<style>
* {
margin: 0;
}
body, html {
width: 100%;
height: 100%;
}
#gfather {
width: 50%;
height: 50%;
background-color: blue;
}
#father {
width: 50%;
height: 50%;
background-color: darkorchid;
}
.child {
width: 50%;
height: 50%;
background-color: green;
}
span {
background-color: yellow;
}
</style>
效果如图:
我们考虑id=gfather的div和id=father的div。(蓝色和紫色的方框)
1. 父元素是块级,子元素是块级
1.1 水平居中
块级元素的居中十分方便,只需一个margin: 0 auto;即可。
#father {
width: 50%;
height: 50%;
background-color: darkorchid;
margin: 0 auto;
}
效果图:(紫色框已经来到了蓝色框的水平中央)
1.2 垂直居中
1.2.1 如果需要被居中的子元素宽高已知
这种情况可以“子绝父相”,通过定位先left、top各偏移50%,使子元素左上角到达中间位置。而后通过margin设置负属性值来调整中央,这个负属性值需要我们人工计算。
可能会有人想这样实现,通过将margin值也设置为负值百分比来达到目的,但这不可行。
margin的百分比值虽然也是参照其父元素的宽高的,但它无法解决我们的问题,因为它只会参照宽度(或高度)一种。
详细介绍可以自己找,这里是其中一篇:
https://www.runoob.com/note/30218
1.2.2 如果需要被居中的子元素宽高未知(可变)
这种情况下的实现显然适用范围更广一些。
方法一
#gfather {
width: 50%;
height: 50%;
background-color: blue;
position: relative;
}
#father {
width: 50%;
height: 50%;
background-color: darkorchid;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
- 利用“子绝父相”
- 四方向偏移设置为0
- margin设为auto
三个齐聚,完成水平垂直居中。
方法二
仍才采用先偏移百分之50,再倒回去一部分的思想。采用CSS3
#gfather {
width: 50%;
height: 50%;
background-color: blue;
position: relative;
}
#father {
width: 50%;
height: 50%;
background-color: darkorchid;
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
}
实现居中
方法三
(这种方法如果直接加入上面代码,会导致宽高百分比被破坏,如果父元素已知固定大小可以用。)
#gfather {
width: 300px;
height: 300px;
background-color: blue;
display: table-cell;
vertical-align: middle;
}
#father {
width: 50%;
height: 50%;
background-color: darkorchid;
margin: 0 auto;
}
方法四
#gfather {
width: 50%;
height: 50%;
background-color: blue;
display: flex;
justify-content: center;
align-items: center;
}
#father {
width: 50%;
height: 50%;
background-color: darkorchid;
}
它会让gfather这个div内部的元素整体居中。
在我的例子中,那个HAHAHAHA会和紫色方框一起居中。
2. 父元素是块级,子元素是行内(或单纯文本)
以id=child的div和内部的span为例。(绿色框 与 黄色背景的文本)
2.1 水平居中
只需设置一个属性
text-align: center;
.child {
width: 50%;
height: 50%;
background-color: green;
text-align: center;
}
2.2 垂直居中
2.2.1 单行文本居中
设置文本行高等于所在区域高度
.child {
width: 50%;
height: 50%;
background-color: green;
line-height: xxx; /*设置line-height与父级元素的height相等,只能用数值*/
text-align: center;
overflow: hidden; /*防止内容超出容器或者产生自动换行*/
}
图片来自网络
这里的缺陷就在于,仍然需要人工计算所在区域(这里是div)高度。
如果父元素设置的是百分比,则无法很好地处理。
2.2.2 多行文本居中
父级元素高度不固定
只能通过内部文本撑开。
通过设置填充物(padding),把文本挤到中间,使它们看起来居中。设置padding的top和bottom要相等。
注意,这里也只能设置px值。
而padding和margin相似,设置百分比只会参考宽(高)一种,同样无法完成之前在margin那里一样的设想。
父级元素高度固定
css中的vertical-align属性,结合display: table把div模拟成table属性。
因此设置父级div的display属性:display: table;
然后添加一个div包含span文本,设置其display:table-cell;和vertical-align:middle;
同上文块级的垂直居中类似。
若有错误或更好的实现方式,还望指正。