这两天试web前端css的时候用到左中右的布局。div放在左边和div放在右边都是通过float实现的。然后中间有个div。但是这里存在一个问题,右边那个div设置float:right后,它并不是跟左边的div对齐的。代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>提交信息</title>
<style type="text/css">
<!--
p {
}
body {
}
#box{
margin:0 auto; /* 居中 这个是必须的,,其它的属性非必须 */
width:100%; /* 给个宽度 顶到浏览器的两边就看不出居中效果了 */
/*text-align:center; 文字等内容居中 */
}
#left{
width:15%;
height:300px;
background-color:blue;
border:2px dotted;
float:left;
}
#main{
margin:0 auto; /*居中 这个是必须的*/
width:60%;
height:500px;
border:1px solid;
text-align:center; /*文字等内容居中*/
}
#right{
width:15%;
height:300px;
background-color:green;
border:2px dotted;
float:right;
}
-->
</style>
</head>
<script language="javascript">
function success(){
alert("提交成功");
document.getElementById("form1").submit();
// 一定要给FORM设ID 如果用名字找是另一个方法
}
</script>
<body>
<div id="box">
<div id="left">
left
</div>
<div id="main">
<form id="form1" method="post" action="myServlet?method=add">
<p>姓名<input name="name" type="text"></p>
<p>电话<input name="phone" type="text"></p>
<p>地址<textarea name ="addr" rows="3" cols="20"></textarea></p>
<p><input type="button" value="提交" onClick="return success()"></p>
</form>
</div>
<div id="right">
right
</div>
</div>
</body>
</html>
参考http://www.w3cplus.com/css/float.html文章后,发现实际上是因为main模块把right模块挤换行了,然后再置右的。那么这里就把right的代码提前,放在main模块之前即可。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>提交信息</title>
<style type="text/css">
<!--
p {
}
body {
}
#box{
margin:0 auto; /* 居中 这个是必须的,,其它的属性非必须 */
width:100%; /* 给个宽度 顶到浏览器的两边就看不出居中效果了 */
/*text-align:center; 文字等内容居中 */
}
#left{
width:15%;
height:300px;
background-color:blue;
border:2px dotted;
float:left;
}
#main{
margin:0 auto; /*居中 这个是必须的*/
width:60%;
height:500px;
border:1px solid;
text-align:center; /*文字等内容居中*/
}
#right{
width:15%;
height:300px;
background-color:green;
border:2px dotted;
float:right;
}
-->
</style>
</head>
<script language="javascript">
function success(){
alert("提交成功");
document.getElementById("form1").submit();
// 一定要给FORM设ID 如果用名字找是另一个方法
}
</script>
<body>
<div id="box">
<div id="left">
left
</div>
<div id="right">
right
</div>
<div id="main">
<form id="form1" method="post" action="myServlet?method=add">
<p>姓名<input name="name" type="text"></p>
<p>电话<input name="phone" type="text"></p>
<p>地址<textarea name ="addr" rows="3" cols="20"></textarea></p>
<p><input type="button" value="提交" onClick="return success()"></p>
</form>
</div>
</div>
</body>
</html>
本文介绍了一种使用CSS float属性实现左右布局的方法,并解决了当右侧div不与左侧div对齐的问题。通过调整HTML结构,将右侧div置于中间div之前,实现了正确的布局效果。
871

被折叠的 条评论
为什么被折叠?



