I have a basic setup like this:
.container {
border:1px solid green;
}
<div class="container">
<div class="parent">
Hello world! I don't want to overlap with the image. Hello world! I don't want to overlap with the image. Hello world! I don't want to overlap with the image.
</div>
<div class="parent">
<div class="child">
<img src="http://i.imgur.com/sQSbV8o.jpg" width="200" height="200">
</div>
</div>
</div>
I want to align the .child
div to the top-right of the .container
. I want to achieve this without position:fixed
or some margin-top:-px
hack, or changing any of the HTML.
Is this insanity possible?
jsFiddle for testing.
I can set float:right
to the .child
div, but obviously, the first parent div is above it.
I can set position:absolute
to the .child
div, and top:0
and right:0
but it overlaps clearly.
Maybe flex-box
insanity is the key? Although compatibility issues...
if a div is fixed or absolute you can use right: 0; to get the div to the right.
We can set the child element as an in-line element, display: inline-block; , and then set the father element as text-align: center; , so that the child element can be horizontally centered.
Method 1: First method is to simply assign 100% width and 100% height to the child div so that it will take all available space of the parent div. Consider this HTML for demonstration: HTML.
Like last time, you must know the width and height of the element you want to center. Set the position property of the parent element to relative . Then set the child's position property to absolute , top to 50% , and left to 50% . This just centers the top left corner of the child element vertically and horizontally.
you can use calc()
in .parent
along with position:absolute
in .child
, and by reading your comments, it won't have the `problem with second parent having content.
.container {
border: 1px solid green;
position: relative;
min-height: 200px;
}
.parent {
max-width: calc(100% - 220px) /* img width + some margin */
}
.child {
position: absolute;
top: 0;
right: 0;
}
<div class="container">
<div class="parent">
Hello world! I don't want to overlap with the image. Hello world! I don't want to overlap with the image. Hello world! I don't want to overlap with the image.
</div>
<div class="parent">
<div class="child">
<img src="http://i.imgur.com/sQSbV8o.jpg" width="200" height="200">
</div>
<p>Hello world! I don't want to overlap with the image. Hello world! I don't want to overlap with the image. Hello world! I don't want to overlap with the image.</p>
<p>Hello world! I don't want to overlap with the image. Hello world! I don't want to overlap with the image. Hello world! I don't want to overlap with the image.</p>
</div>
</div>
You could set the display for the parent divs to table-cell:
.parent {
display:table-cell;
vertical-align:top;
}
jsFiddle example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With