首页 > 代码库 > 两个div横向排列,顶端对齐的方式。

两个div横向排列,顶端对齐的方式。

1、左右两个div都设置为float:left,如果右边div没有设置宽度,右边div的宽度会根据div里的内容自动调整。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"
/>

<title>无标题文档</title>

<style type="text/css">

* { margin: 0; padding:0;}

.left {

float:
left;

width: 200px;

height: 200px;

background:#009966;

}

.right {

height: 200px;

background: #FF6633;

float:left;

}

</style>

</head>



<body>

<div class="left">I am left</div>

<div class="right">I am right</div>

</body>

</html>

2、只有左侧div设置为float:left,右侧div设置overflow:auto;,右侧div将会占据整个右侧剩余宽度。


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"
/>

<title>无标题文档</title>

<style type="text/css">

* { margin: 0; padding:0;}

.left {

float:
left;

width: 200px;

height: 200px;

background:#009966;

}

.right {

height: 200px;

background: #FF6633;

overflow:auto;

}

</style>

</head>



<body>

<div class="left">I am left</div>

<div class="right">I am right</div>

</body>

</html>

3、两个div都设置为display:
inline-block;这样可能会出现两个div顶端不对齐的情况,可以在右侧div设置
vertical-align: top;


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"
/>

<title>无标题文档</title>

<style type="text/css">

* { margin: 0; padding:0;}

.left {

display:
inline-block;

width: 200px;

height: 200px;

background:#009966;

}

.right {

height: 200px;

background: #FF6633;

display:
inline-block;

vertical-align: top;   //与左侧div顶部对齐

}

</style>

</head>



<body>

<div class="left">I am left</div>

<div class="right">I am right</div>

</body>

</html>