Denis Rozimovschii Denis Rozimovschii - 5 months ago 7
CSS Question

Relative and absolute positioning. Force a logo move to the corner

Suppose I have such a situation:

enter image description here

You can see a few main parts:


  • The panel (border red)

  • The image

  • The logo

  • The title



And I need this setup:

enter image description here

So the logo needs to get up. Usually, every time I try to make the image
absolute
and the logo
relative
, then float it to right it works, but I loose the title which also goes under the image.

And I can't make the title relative and push it from top with some value, because the image is responsive and changes it's
height
.

Here is the code I'm using.

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<style>
.body {
width: 100%;
}

.panel {
border: 1px solid red;
background-color: blue;
margin: 50px;
}
img {
width: 100%;
}

.logo {
background-color: red;
border: 1px solid yellow;
width: 100px;

}
</style>
</head>
<body>

<div class="panel">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTVxPtnNvc1ZwknRSdJZIPjrmUHitXdUU_-TT3wuIF-mWND6sXV" class="img-responsive" alt="picture nature">
<div class="logo">
I'm a logo
</div>
<h1>I'm a title, hello</h1>
</div>

</body>
</html>

Answer

So I've added position:relative to the container and position:absolute; top:0; right:0 to the logo

.body {
    width: 100%;
}
.panel {
    border: 1px solid red;
    background-color: blue;
    margin: 50px;
    position:relative;
}
img {
    width: 100%;
    height: 200px;
}
.logo {
    background-color: red;
    border: 1px solid yellow;
    width: 100px;
    position:absolute;
    top:0;
    right:0;
}

https://jsfiddle.net/3gusz58x/

Since the image is not moving and needs to change it's dimensions, you can just make the logo move to wherever you need it to with absolute. If you make it absolute, you need to give its container (or at least the container you would like it to be 'contained' in) position:relative; so it has somewhere to be.