我试图将 h2 与标题的右侧对齐,同时保持与现在相同的垂直方向,但向右浮动似乎不起作用。有什么想法吗?
<div class="header-bg">
<h1>
Heading
</h1>
<h2>
this is where you write more things
</h2>
</div>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact Me</a></li>
<li><a href="#about">About</a></li>
</ul>
这是 CSS:
body {
margin: 0;
}
.header-bg {
background: lightblue;
}
h1, h2 {
display: inline-block;
margin: 10px 10px;
/* border: solid black 1px; */
}
}
h2 {
/* border: solid black 1px; */
float: right;
}
ul {
clear: both;
list-style: none;
margin: 0;
padding: 0;
background: #333;
overflow: hidden;
}
这里是 jsfiddle 的链接:https://jsfiddle.net/n8xjk4ax/3/
最佳答案
首先,删除无关的 }
,如评论所述。
现在,随着 h2
float ,它将不再与 h1
位于同一基线上。如果您确实希望如此,有几种可能性。
不要 float 它,而是对齐容器中的元素
body { margin: 0; } .header-bg { background: lightblue; padding: 10px; text-align: justify; -moz-text-align-last: justify; text-align-last: justify; } h1, h2 { display: inline-block; margin: 0; /* border: solid black 1px; */ } ul { clear: both; list-style: none; margin: 0; padding: 0; background: #333; overflow: hidden; } li a { display: block; color: white; text-decoration: none; text-align: center; padding: 14px 16px; } li { float: left; } li:last-child { float: right; } li a:hover { background-color: #111; color: white; }
<div class="header-bg"> <h1> Heading </h1> <h2> this is where you write more things </h2> </div> <ul> <li><a href="#home">Home</a></li> <li><a href="#news">News</a></li> <li><a href="#contact">Contact Me</a></li> <li><a href="#about">About</a></li> </ul>
或者,如果您确实想要 float ,容器还需要
overflow:hidden
来适应狭窄的屏幕。您应该为 h1 和 h2 提供相同的指标。使用行高是最简单的。body { margin: 0; } .header-bg { background: lightblue; overflow:hidden; } h1, h2 { display: inline-block; margin: 0 10px; line-height: 4rem; /* border: solid black 1px; */ } h2 { /* border: solid black 1px; */ float: right; } ul { clear: both; list-style: none; margin: 0; padding: 0; background: #333; overflow: hidden; } li a { display: block; color: white; text-decoration: none; text-align: center; padding: 14px 16px; } li { float: left; } li:last-child { float: right; } li a:hover { background-color: #111; color: white; }
<div class="header-bg"> <h1> Heading </h1> <h2> this is where you write more things </h2> </div> <ul> <li><a href="#home">Home</a></li> <li><a href="#news">News</a></li> <li><a href="#contact">Contact Me</a></li> <li><a href="#about">About</a></li> </ul>
关于html - 让 h2 内联到 h1 并在标题中向右浮动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47623167/