以下代码不会将<p>
文本放在中心,而是放在宽度的约60/70%左右。在后台发生了什么/为什么这不起作用?
<div>
<img src="logo.jpg" style="float: left;">
<p style="text-align: center;"> hello world </p>
<img src="logo2.jpg" style="float: right;">
</div>
答案 0 :(得分:3)
您可以根据需要使用flexbox对齐项目,阅读每个用途的评论并尝试调整它们:)
.flex-container {
display: flex; /*Generates a flexbox layout with default flex direction as row */
width: 100%; /* Not really required */
align-items: center; /*Aligns contents vertically */
justify-content: space-between; /*Aligns contents horizontally */
text-align: center; /*Aligns further text in the center */
/* flex-direction:row; By default its row, you can change to column for vertical alignment */
/* flex-flow:row wrap; To wrap items in other row when no more can be fit in the same row*/
}
<div class="flex-container">
<img src="http://via.placeholder.com/100x100" >
<p > hello world </p>
<img src="http://via.placeholder.com/100x100" >
</div>
答案 1 :(得分:1)
请考虑以下 x3 方法,如下面嵌入的代码段所示:
p
元素移到浮动元素下面
绕过由浮动元素引起的降压效果 img
元素中嵌套p
个元素
允许段落标记占用嵌套浮动元素的完整可用宽度img
元素中嵌套绝对定位的 p
元素
从正常文档流中删除嵌套图像代码段示范:
注意:此片段纯粹是为了演示上述方法,在假设图像大小的情况下采取了自由。
code {
background: #dadada;
padding: 3px;
}
* {
font-family: arial;
}
<h3>1) Move <code>p</code> element below floated elements</h3>
<div>
<img src="https://placehold.it/100x100" style="float: left;">
<img src="https://placehold.it/100x100" style="float: right;">
<p style="text-align: center;"> hello world </p>
</div>
<div style="clear: both;"></div>
<h3>2) Nest <code>img</code> elements within the <code>p</code> element</h3>
<div>
<p style="text-align: center;">
<img src="https://placehold.it/100x100" style="float: left;">
hello world
<img src="https://placehold.it/100x100" style="float: right;">
</p>
</div>
<div style="clear: both;"></div>
<h3>3) Nest <em>absolutely positioned</em> <code>img</code> elements within the <code>p</code> element</h3>
<div>
<p style="text-align: center; position: relative;">
<img src="https://placehold.it/100x100" style="position: absolute; left: 0;">
hello world
<img src="https://placehold.it/100x100" style="position: absolute; right: 0;">
</p>
</div>
答案 2 :(得分:0)
尝试使用flexbox,它可以解决所有问题。
尽管如此,父母的justify-content: space-between
可用于根据需要放置内容。
div {
display: flex;
justify-content: space-between;
}
<div>
<img src="http://via.placeholder.com/350x150" style="float: left;">
<p style="text-align: center;"> hello world </p>
<img src="http://via.placeholder.com/350x150" style="float: right;">
</div>