How to position children with respect to parent in CSS?
I am using HTML 5 with CSS 3. The scenario is like this.
<div style="margin-top: 50px; background-colo开发者_如何学JAVAr: red; padding: 10px 0px 10px 0px; width: 100%">
<span>This text must be in center of div</span>
<a href="somepage.html"><img src="/image.jpg" alt="This image must be on left side of div"/></a>
</div>
The text and image must be in single line. How do I do that ?
Example
To position an element with respect to its parent, you give the parent any position value besides static
(generally relative
) and the child position: absolute
.
In keeping with your inline CSS...
<div style="margin-top: 50px; background-color: red; padding: 10px 0px 10px 0px; width: 100%; text-align: center; position: relative;">
This text must be in center of div
<img src="/image.jpg" alt="This image must be on left side of div" style="position: absolute; left: 0;"/>
</div>
jsFiddle.
However you should consider using classes, ids and an external stylesheet.
SPAN and IMG are both inline elements so they should be appear next to each other by default. If you want the IMG to appear on the left and the SPAN text after it...
<img /><span />
How about this? I edited the code based on your comment. The caveat is that the line-height of the P tag must be set to the height of the div in order to get the P to center vertically as well as horizontally.
<style>
.myDiv{
background-image: url('../pathToImage/image.jpg');
background-repeat: no-repeat;
background-position: center left;
margin-top: 50px;
background-color: red;
width: 100%;
text-align: center;
height: 250px;
}
.myDiv P
{
line-height:250px;
}
</style>
<div class="myDiv">
<p>This text must be in center of div.</p>
</div>
精彩评论