在写网页的头部导航栏时,有时会需要类似的功能,左边放一个logo,右边是一排导航栏。抽象一下,如图:
实现思路
利用绝对定位和相对定位的功能灵活布置div的位置,并用transform作最后的微调。代码及注释:
<!DOCTYPE html>
<html>
<head>
<title>
div
</title>
<style type="text/css">
.div1 {
background-color: gray; /* 背景色 */
height: 500px; /* 设置父div的长宽 */
width: 600px;
margin: auto; /* 在浏览器中水平居中 */
position: relative; /* 与子div的position联用 */
}
.div2 {
background-color: red;
height: 150px;
width: 150px;
text-align: center; /* 文字居中 */
position: absolute; /* 使得div2相对于div1的左上角定位 */
top: 50%; /* div2左上角垂直居中 */
left: 0%; /* div2贴在div1的左边 */
transform: translate(0%,-50%); /* 往上移动自身的百分之50% */
}
.div3 {
background-color: green;
height: 150px;
width: 150px;
text-align: center;
position: absolute;
top: 50%;
right: 0%;
transform: translate(0%,-50%);
}
</style>
</head>
<body>
<div class="div1">
<div class="div2">1</div>
<div class="div3">2</div>
</div>
</body>
</html>
如果用float(分别在div中写上float:left; float:right;),最后没法垂直居中
也可根据div的大小,直接在top属性中设置具体距离,但那样必须知道div的具体高度,且扩展性不强。故使用transform是比较好的方法