我有一个包含 div、h1 和 div 的 css header 。我面临着将 div 内容向左对齐、标题向中间对齐以及第二个 div 向右水平对齐并且第二个 div 的内容相互重叠的挑战。
CSS 片段
#header {
height: 166px;
background-color: #ccc;
font-weight: bold;
color: black;
margin-bottom:3px;
padding: 2px;
text-align: center;
width: 100%x;
}
#footer {
height: auto;
background-color: #ccc;
font-size: 20px;
font-weight: bold;
color: black;
margin-top: 3px;
padding: 2px;
text-align: center;
width: 100%x;
}
html 片段
<div id="header">
<div style="float:left; margin-left:40px;">
<img src="${contextPath}/resources/images/chat1.png" width="496" height="90"/>
</div>
<h3 align="center"><strong>Chat Panel</strong></h3>
<div align="right">
<img src="${contextPath}/resources/images/chat2.png" />
<form method="post" action="/logout">
<input type="submit" value="Leave Chat"/>
</form>
</div>
</div>
下面是我正在尝试的示例
div content h1 content second div
请协助!
最佳答案
也许像这样,你使用 flex
来排列它们
#header {
height: 166px;
background-color: #ccc;
font-weight: bold;
color: black;
margin-bottom: 3px;
padding: 2px;
text-align: center;
width: 100%x;
display: flex;
}
#header * {
flex: 1;
}
#header div:last-child {
text-align: right;
}
#header h3 {
margin-top: 35px;
}
#footer {
height: auto;
background-color: #ccc;
font-size: 20px;
font-weight: bold;
color: black;
margin-top: 3px;
padding: 2px;
text-align: center;
width: 100%x;
}
<div id="header">
<div>
<img src="http://placehold.it/200x50/f00" width="296" height="90" />
</div>
<h3 align="center"><strong>Chat Panel</strong></h3>
<div>
<img src="http://placehold.it/50x50/ff0" />
<form method="post" action="/logout">
<input type="submit" value="Leave Chat" />
</form>
</div>
</div>
如果您需要针对较旧的浏览器,可以使用 display: table-cell
来完成
#header {
height: 166px;
background-color: #ccc;
font-weight: bold;
color: black;
margin-bottom: 3px;
padding: 2px;
text-align: center;
width: 100%;
display: table;
}
#header * {
display: table-cell;
text-align: center;
vertical-align: middle;
}
#footer {
height: auto;
background-color: #ccc;
font-size: 20px;
font-weight: bold;
color: black;
margin-top: 3px;
padding: 2px;
text-align: center;
width: 100%x;
}
<div id="header">
<div>
<img src="http://placehold.it/200x50/f00" width="296" height="90" />
</div>
<h3 align="center"><strong>Chat Panel</strong></h3>
<div>
<img src="http://placehold.it/50x50/ff0" />
<form method="post" action="/logout">
<input type="submit" value="Leave Chat" />
</form>
</div>
</div>
关于html - 将一个 div 水平对齐到左侧,一个标题对齐到中心,一个 div 水平对齐到右侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38703676/