css中设置居中方法里float用法的认识
最近在学习CSS里几种将元素居中的方法,对float的用法不是很理解,特别去找了相关资料,自己稍加总结,在这里记录下来!
- float的基本用法
- float在元素水平居中用法
#float
float,顾名思义,浮动的。类似于word里设置某种文字环绕的效果,这里参考float
Pushes the element to either the left or right side. The following siblings will wrap around the floating element
- float:none
Removes any previously defined float value. The element will remain in the natural flow of the page. - float:left
Moves the element to the left side of its container. The following elements will wrap around it and fill the space remaining on the right. - float:right
Moves the element to the right side of its container. The following elements will wrap around it and fill the space remaining on the left.
这部分的内容可以在CSS帮助文档里找到float这个关键字的用法,下面主要是float在水平居中使用的方法。
用法
通过给父元素设置 float,然后给父元素设置 position:relative 和 left:50%,子元素设置 position:relative 和 left: -50% 来实现水平居中。Reference
例如:
<body>
<div class="container">
<ul>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
</div>
</body>
对应的CSS代码:
<style>
.container{
float:left;
position:relative;
left:50%
}
.container ul{
list-style:none;
margin:0;
padding:0;
position:relative;
left:-50%;
}
.container li{float:left;display:inline;margin-right:8px;}
</style>
假想ul层的父层(即下面例子中的div层)中间有条平分线将ul层的父层(div层)平均分为两份,ul层的css代码是将ul层的最左端与ul层的父层(div层)的平分线对齐;而li层的css代码则是将li层的平分线与ul层的最左端(也是div层的平分线)对齐,从而实现li层的居中。
那这里的用法我就可以理解了,float定义了一个漂浮着的元素块,我们使用position来规定这个元素块的位置。div里的position是相当于浏览器窗口的位置,ul里定义的位置是相当于div的位置,li则使用display:inline;
来实现居中 ,这里可以参考Ref2
- 完整的代码为:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>不定宽块状元素水平居中</title>
<style>
.container{
float:left;
position:relative;
left:50%
}
.container ul{
list-style:none;
margin:0;
padding:0;
position:relative;
left:-50%;
}
.container li{float:left;display:inline;margin-right:8px;}
/*下面是代码任务区*/
.wrap{
clear:both;
float:left;
position:relative;
left:50%
}
.wrap-center{
background:#ccc;
position:relative;
left:-50%;
}
</style>
</head>
<body>
<div class="container">
<ul>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
</div>
<!--下面是代码任务区-->
<div class="wrap">
<div class="wrap-center">我们来学习一下这种方法。</div>
</div>
</body>
</html>
显示结果:
这里值得注意的是,在这段代码里:
.wrap{
clear:both;
float:left;
position:relative;
left:50%
}
加入了:
clear:both;
这里的作用是清除浮动的效果(也即是float left 和float right的效果),首先我们理解一下clear,顾名思义就是清除的意思,both的意思是全部,那连起来就是清除全部样式,不过这个样式主要是用于对多个div浮动的清除,如float:left,如果不清除,很容易对下面的div造成显示错位。Ref3
第一次用Markdown写还有点不习惯,得去补补知识。