通过上篇css 的规律摸索之路(一)css之三角形的规律及变化,我们已经知道css三角形是怎么回事,现在我们来看看另外一个,常见的应用:css之居中问题(垂直居中与水平居中)
垂直居中
单行文本垂直居中
首先,说说最简单的常见居中方式-单行文本垂直居中:
<div class="single_line_text_box">
<div class="single_line_text">单行文本垂直居中</div>
<!-- <img src="" alt="" class="single_line_text"> -->
</div>
<style>
.single_line_text_box {
height: 100px; width: 100%; background: #333; line-height: 100px; text-align: center;
}
.single_line_text {
vertical-align: middle; position: relative;
}
</style>
这方式很简单,我们常用来做单行文本的垂直居中,它的用处也只限与垂直居中包含文本的容器和图片,并且宽高不能设定不然无法居中。
说明:通过父容器设定line-height,以及子元素设定vertical-align: middle;来实现,其中子元素垂直居中不能设定宽度和高度,子元素的内容必须为文本或图片,且文字尽量不能换行不然会溢出
display:table的方式
下来就是display:table的方式,这是一种借助表格样式的居中方式:
<div class="table_parent">
<div class="table_child">说明:通过父容器设定display: table;,以及子元素设定display: table-cell; vertical-align: middle;来实现,其中子元素设定的高度宽度无效,子元素的内容任意,内容为文字时自动换行照样居中</div>
</div><br>
<div class="table_parent">
<div class="table_child"><div class="table_child_content">display:table的方式</div></div>
</div>
<style>
.table_parent {
display: table; height: 100px; width: 100%; background: #eee;