Bootstrap CSS导航栏Logo无法左移、文字未排列到Logo右侧求助
问题原因
一共3个核心错误导致布局异常:
- HTML类名拼写错误:
- 文字容器的类写的是
navar-brand,正确Bootstrap类名是navbar-brand,少写了字母b,导致自定义的.navbar-brand样式完全没生效,也没吃到Bootstrap自带的导航栏品牌位浮动样式,所以文字没法跑到Logo右侧,直接换行掉到Logo下方 - Logo链接的响应式类写的是
visble-md,正确类名是visible-md,少写了字母i,导致中大屏下Logo的显示逻辑异常
- 文字容器的类写的是
- CSS属性用错:给
h1加的object-position: right完全无效,这个属性只对<img>、<video>这类替换元素生效,普通文本元素用这个属性没有任何布局效果 - 单位使用不规范:
h1的字体大小用了1.5cm这个物理打印单位,在网页端渲染很容易出现尺寸溢出,挤压布局空间,也是Logo没法正常靠左的诱因之一
修复方案
- 修正所有HTML类名拼写错误
- 删掉无效的
object-position属性,给.navbar-brand补全浮动逻辑,和左侧Logo保持同方向排列 - 把字体的
cm单位换成网页常用的相对单位em/rem/px,避免尺寸溢出 - 如果需要Logo再往左靠,直接调整
#logo-img的左外边距即可
修正后代码
CSS部分(styles.css)
body { font-size: 16px; color: #fff; background-color: #F5EEE0; font-family: 'Oxygen', sans-serif; } /** HEADER **/ #header-nav { background-color: #AE7F60; border-radius: 0; border: 0; } #logo-img { background: url('../images/coffee-shop-logo_large.png') no-repeat; width: 150px; height: 150px; /* 要让Logo更靠左,把最后一个0改成负数,比如margin: 10px 15px 10px -10px; */ margin: 10px 15px 10px 0; } .navbar-brand { padding-top: 25px; /* 补浮动,和左侧Logo并排 */ float: left; } .navbar-brand h1{ /* 咖啡店名称 */ font-family: 'Lora', sans-serif; color: #B35840; /* 替换cm为相对单位,避免溢出 */ font-size: 2em; text-transform: uppercase; font-weight: bold; text-shadow: 1px 1px 1px #222; margin-top: 0; margin-bottom: 0; line-height: .75; } .navbar-brand a:hover, .navbar-brand a:focus{ text-decoration: none; }
HTML部分
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>coffee cafe</title> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/styles.css"> <link href='https://fonts.googleapis.com/css?family=Oxygen:400,300,700' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Lora' rel='stylesheet' type='text/css'> </head> <body> <header> <nav id="header-nav" class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <!-- 修正visible类名拼写 --> <a href="index.html" class="pull-left visible-md visible-lg"> <div id="logo-img" alt="Logo image"></div> </a> <!-- 修正navbar-brand类名拼写 --> <div class="navbar-brand"> <a href="index.html"><h1>Coffee Place</h1></a> </div> </div> </div> </nav> </header> <!-- jQuery (Bootstrap JS plugins depend on it) --> <script src="js/jquery-3.6.0.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/script.js"></script> </body> </html>
补充说明:如果需要调整Logo的左偏移距离,直接修改#logo-img的margin属性最后一个值(左外边距)即可,需要往左移就设为负值,往右移就增大正值。
内容的提问来源于stack exchange,提问作者user19452249
相关产品推荐
相关产品推荐

