[英]How can I vertically-align child elements of a div while keeping them floated to the left and right?
I am re-writing parts of an existing website and would very much like to clean up some things. 我正在重写现有网站的部分内容,非常想清理一些内容。 Currently, where certain child elements in a parent div are
float
ed (left and right), I have to use margin-top: 7px;
当前,在父div中的某些子元素
float
(左和右)的地方,我必须使用margin-top: 7px;
to push the left-floated child element down a bit so it's inline with the right-floated child element. 将左浮动的子元素向下推一点,使其与右浮动的子元素内联。
I don't like doing this. 我不喜欢这样
Below is what I expect to see: 以下是我希望看到的:
But that's not what I see. 但这不是我所看到的。 Instead, I see this:
相反,我看到了:
So I tried a few things to see if I could fix it. 因此,我尝试了一些尝试以查看是否可以修复它。 The original code is:
原始代码是:
<div id="bottomHeader">
<p>Some slogan here</p>
<ul id="SocialLinks">
<li><a href="#"><img src="~/!/Assets/Images/Twitter.png" alt="" /></a></li>
<li><a href="#"><img src="~/!/Assets/Images/Facebook.png" alt="" /></a></li>
</ul>
</div>
#bottomHeader { width: 80%; margin: 0 auto; }
#bottomHeader > p { text-align: left; }
#bottomHeader > p { text-align: right; }
Which aligns them left and right, but the p
element is higher than the ul
element. 左右对齐,但
p
元素高于ul
元素。 I realised that this is because both elements have a default width of 100%. 我意识到这是因为两个元素的默认宽度均为100%。 So the
p
element is pushing the ul
element down beneath it. 因此,
p
元素将ul
元素推到其下方。
So then I just thought that if I make both elements have a max-width of 50%, it'll be alright. 所以然后我只是想,如果我使两个元素的最大宽度都为50%,那就没问题了。 But, nope.
但是,不。 When I do that, the ul element (which is supposed to be right-aligned), is appearing in the center somewhere (almost as if it's left-aligned).
当我这样做时,ul元素(应该是右对齐的)出现在中间的某个地方(几乎好像是左对齐的)。 So then I changed the code to:
因此,我将代码更改为:
#bottomHeader { width: 80%; margin: 0 auto; }
#bottomHeader > p { width: 50%; float: left; }
#bottomHeader > p { width: 50%; float: right; }
Which worked. 哪个有效。 However , now the parent div (see dark blue rectangle in pic above) has a height less than the height of its child elements, like so:
但是 ,现在父div(请参见上图的深蓝色矩形)的高度小于其子元素的高度,如下所示:
But that's still not quite right. 但这还不太正确。 'Cause now it looks like the child elements of the div are outside and below their parent div.
因为现在看起来div的子元素在其父div的外部和下方。 And it also breaks the layout a little.
而且它还会破坏布局。
How can I vertically-align child elements of a div while keeping them floated to the left and right? 如何在使div的子元素垂直浮动的同时保持左右浮动?
Maybe display: inline-block
is what you are looking for. 也许
display: inline-block
是您想要的。
It makes the element act as both block-level box, and an inline-level box. 它使元素既充当块级框又充当内联级框。
Like this: 像这样:
#bottomHeader {
width: 80%;
margin: 0 10% 0 10%;
background:pink;
display:inline-block;
height: auto;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.