问题
I have a "problem" that at first sight didn't look like one. So, I have a parent div containing to childs. The one child will contain text, and the other a picture. Both are inline-block elements (they need to be positioned next to each other), and have set widths. Now, when the picture div is bigger than the text div, the parent inherits the height of that div (the biggest one). But the second child (which is smaller) is placed at the bottom of that div. What I want is to have that div always at the top.
I've tried
top: 0px;
and stuff, but it doesn't work. It just sticks to the bottom.
Here's my sample (html) code:
<div id="parent">
<div id="child1"> Assassin's Creed IV: Black Flag: Gameplay Reveal Trailer - Chart your course through a treacherous and unpredictable world as the Assassin's Creed series hits the high seas in Assassin's Creed IV: Black Flag. <a href="http://bit.ly/Zny5pI">http://bit.ly/Zny5pI</a> </div>
<div id="child2"> <img width="300px" src="http://sphotos-a.ak.fbcdn.net/hphotos-ak-ash3/536527_10151407411789285_1500143344_n.jpg" /> </div>
</div>
And here's the CSS:
#parent {
border: 2px solid green;
}
#child1 {
border: 2px solid black;
display: inline-block;
width: 400px;
margin: 2px;
top: 0px;
}
#child2 {
border: 2px solid red;
display: inline-block;
width: 300px;
}
I just took a post on Facebook by GameTrailers as an example.
Could anyone help me by solving this "problem"? I don't think it's hard, but it's been a while since I've worked with CSS, and it's not my favorite "coding language" :P
Thanks in advance.
回答1:
Rather than display: inline
try float: left
.
回答2:
Try adding the CSS rule:
vertical-align:top;
to all your inline-block divs that you want top-aligned
Good luck!
回答3:
There are a few different ways of doing this, they should all work.
1:
#parent > div{
vertical-align: top;
}
2:
#parent{
position: relative;
}
#parent > div{
position: absolute;
top: 0px;
}
3:
#parent > div{
float: left;
}
回答4:
#parent > div {vertical-align: top}
回答5:
You can ALWAYS do it with absolute positioning although this usually causes issues down the road, try and stick to relative positioning.
http://jsfiddle.net/C6n86/
#parent {
border: 2px solid green;
width: 504px;
margin: 0px;
padding: 0px;
position: relative;
float: left;
}
#child1 {
position: absolute;
top: 0px;
float: left;
height: 279px;
color: white;
}
#child2 {
position: absolute;
top: 0px;
float:left;
}
来源:https://stackoverflow.com/questions/15621489/make-div-stay-in-top-of-parent