Overlay image on div

Viewed 526

I want to set image overlay a div. I want to get this : enter image description here

I used left and top for image position but it doesnt work and I dont get the excepted result. This is what I did :

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    ### i use div to integrate image here ###
    div(
      img(src = "https://images-na.ssl-images-amazon.com/images/I/61Jigwd1kKL._AC_SL1500_.jpg", 
            style = "left: 16px; width: 10%; border-radius: 50%; top: -60px;")
      ),
    div(id = "id", style = "width: 500px; max-width: 100%; margin: 0 auto; padding: 20px;",
        wellPanel(
          tags$h2("my title", class = "text-center"),
          div(actionButton("btn1", "click here"))
          )
    )
  )
)

server <- function(input, output) { }

shinyApp(ui, server)

but i get this : enter image description here

Some help would be appreciated

2 Answers

The reason why your css didn't seem to work is because the divs have the wrong position setting.

There are five position settings: static, relative, absolute, fixed, sticky.

All elements are position:static by default, and top / left / z-index / etc do not work with static elements.

There are a few things that I generally change on every website project I do, so I add something like this to the top of every CSS page:

* {position:relative; box-sizing:border-box; margin:0; padding:0; }

This is called a CSS Reset, and many people have devised more complicated ones (as web standards evolve, CSS Resets also get adjusted).

In your question code, the one to understand is position:absolute and the difference between position: absolute and position: relative.

Here's a good description. The most important sentence in the article is this one: Remember that these values will be relative to the next parent element with relative (or absolute) positioning. In other words, if you specify position:absolute; top:0; left:0; somewhere but forget that all other divs on the page are still at the default (position:static), your absolute div could jump to the top of the page and be top:0; left:0; off the body! Generally, you want to make sure the parent div (container) is not still position: static.

I won't do a demo since Lundstromski's answer has done a great job with that.

Use position: relative on the parent and position: absolute on the child.

div {
  width: 400px;
  height: 200px;
  background-color: lightcoral;
  margin: auto;
}

.parent {
  position: relative;
}

.child {
  position: absolute;
  top: -15px;
  left: -15px;
  background-image: url('https://picsum.photos/200');
  width: 100px;
  height: 100px;
}
<div class="parent">
  <div class="child">
  </div>
</div>

Related