1、居左:
对要靠左对齐(局左)的div样式加float:left。
示例代码:
css部分:
<style>
.divcss5-left{float:leftwidth:250pxheight:50pxborder:1px solid #F00}
</style>
HTML部分:
<div class="divcss5-left">此DIV靠左对齐显示</div>
2、居右:
对要靠右对齐(局右)的div样式加float:right。
示例代码:
css部分:
<style>
.divcss5-right{float:leftwidth:250pxheight:50pxborder:1px solid #F00}
</style>
HTML部分:
<div class="divcss5-right">此DIV靠右对齐显示</div>
3、居中:
对要居中对齐的div样式加margin:0 auto,不再需要加float样式。
示例代码:
css部分:
<style>
.divcss5-cent{margin:0 autowidth:250pxheight:50pxborder:1px solid #F00}
</style>
<div class="divcss5-cent">此DIV居中右对齐显示</div>
扩展资料:
CSS清除浮动:
浮动:因为使用了float:left或float:right或两者都是有了而产生的浮动。
对父级设置适合CSS高度:
对父级设置适合高度样式清除浮动,一般设置高度需要能确定内容高度才能设置。
示例代码:
css部分:
.divcss5{ width:400pxborder:1px solid #F00background:#FF0 height:102px}
.divcss5-left,.divcss5-right{width:180pxheight:100px
border:1px solid #00Fbackground:#FFF}
divcss5-left{ float:left}
.divcss5-right{ float:right}
HTML部分:
<div class="divcss5">
<div class="divcss5-left">left浮动</div>
<div class="divcss5-right">right浮动</div>
</div>
<style>.head{
width:100%
height:60px
}
.main{
width:70%
height:400px
float:left
}
.main{
width:30%
height:400px
float:right
}
.footer{
width:100%
height:60px
}
</style>
<div class ="head">这里是head区域</div>
<div class ="main">这里是主要内容区域</div>
<div class="main_left">这里是右侧区域</div>
<div class="footer">这里是页脚区域</div>
因为“text-align:center”控制的是文本居中,div居中可以用外边距margin来实现。
1、新建html文件,在body标签中添加div标签,div标签中的内容为“演示文本”,添加题目中的css样式,为了方便演示,给div标签添加灰色背景,这时可以发现div靠近浏览器的左侧,文字在div中居中:
2、为div标签添加新的外边距“margin”属性,属性值为“0 auto”,“0”指的是上下外边距为0,“auto”指的是左右外边距为自适应:
3、这时无论浏览器的宽度是多少,div都会在浏览器上水平居中: