行内块元素上下错位问题
行内块上下错位的原因:
不同的标签,浏览器默认的对齐方式(vertical-align:baseline)不同,
比如图片默认顶对齐,文字默认底对齐。
所以当文字旁边搭配图片时,发现图片比文字靠上,原来默认的情况是图片顶对齐而文字底对齐,通过设置css属性可以使得图片与文字对齐。
解决方法:
- 添加vertical-align属性;
- 添加浮动float
- 将行内块元素改成块级元素,这样vertical-align对块级元素无效
vertical-align 属性设置元素的垂直对齐方式。
代码片
.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>行内块元素上下错位问题</title>
<style type="text/css">
div{
display:inline-block;
}
.div1{
width: 200px;
height: 300px;
/* 为了方便观察,设置颜色 */
background: red;
/*vertical-align: bottom;*/
}
.div2{
width:200px;
height: 200px;
/* 为了方便观察,设置颜色 */
background: #0000FF;
/*把元素的顶端与行中最低的元素的顶端对齐:*/
/*vertical-align: bottom;*/
}
</style>
</head>
<body>
<div class="div1">
div1
</div>
<div class="div2">
div2
</div>
</body>
</html>
原图:
(即解决行内块元素上下错位的问题):
代码片
.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>行内块元素上下错位问题</title>
<style type="text/css">
div{
display:inline-block;
}
.div1{
width: 200px;
height: 300px;
/* 为了方便观察,设置颜色 */
background: red;
vertical-align: bottom;
}
.div2{
width:200px;
height: 200px;
/* 为了方便观察,设置颜色 */
background: #0000FF;
vertical-align: bottom;
}
</style>
</head>
<body>
<div class="div1">
div1
</div>
<div class="div2">
div2
</div>
</body>
</html>
(即解决行内块元素上下错位的问题)
对于img 和 input 行内块元素
代码片
.
/*图片 img*/
.logoImg {
position: relative;
width: 200px;
height: 39px;
left: 15%;
/*vertical-align: bottom;*/
}
/*input 输入框*/
.search>.search1 {
position: relative;
height: 29px;
width: 200px;
left: 55%;
background: url(images/search2.jpg) right no-repeat;
/*vertical-align: bottom;*/
}
原图:
代码片
.
.logoImg {
position: relative;
width: 200px;
height: 39px;
left: 15%;
vertical-align: bottom;
}
.search>.search1 {
position: relative;
height: 29px;
width: 200px;
left: 55%;
background: url(images/search2.jpg) right no-repeat;
vertical-align: bottom;
}
添加vertical-aglin后的图片(即解决行内块元素上下错位的问题)
vertical-align的解释