How can I vertically-align child elements of a div while keeping them floated to the left and right?

StackOverflow https://stackoverflow.com/questions/23691484

  •  29-07-2023
  •  | 
  •  

質問

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 floated (left and right), I have to use 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:

Expected Result

But that's not what I see. Instead, I see this:

Current Result

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. I realised that this is because both elements have a default width of 100%. So the p element is pushing the ul element down beneath it.

So then I just thought that if I make both elements have a max-width of 50%, it'll be alright. 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). 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:

Almost got it

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. 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?

役に立ちましたか?

解決

Maybe display: inline-block is what you are looking for.

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; 
}

SAMPLE

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top