skip to Main Content

I want to put a side bar on top of an image, with the same width as the image. Neither width: inherit|100% work.

CSS

       body {
            display: flex;
        }

        #main-pic {
            width: 40%; 
            height: 700px;
        }

        #main-pic>img {
            width: 100%;
            height: 100%;
        } 

        #logo-holder {
            width: inherit; 
            height: 100px;
            background-color: brown;
            position: absolute;
            top: 50%;
        }

HTML

    <div id="main-pic">
        <img src="myFlower.JPG" alt="My Flower">
        <div id="logo-holder"></div>
    </div>

    <div id="main-text">
        <p>This is the part for text</p>
    </div> 

In this example, I use width: inherit, the #logo-holder is a bit longer than the image. I tried width: 100%, it’s stretched across browser. Can someone explain and suggest a solution?

2

Answers


  1. From the name of your image (myflower.jpg) and your description of what you are trying to do, it sounds like you want your sidebar to have some pretty flowers in the background, as a decorative addition to your page.

    In that case, because the purpose of the image is style rather than substance, it belongs in your style rules, your CSS. Add a background declaration to your sidebar style rule which references your image of flowers. Your logo image, however, is part of your content rather than being purely aesthetic, so it should remain referenced from your HTML.

    This answer explains the same thing using different words.

    body {
      display: flex;
      margin: 0;
    }
    
    #sidebar {
      width: 40%; 
      height: 700px;
      background: url(http://picsum.photos/id/106/800/1600);
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    #logo {
      width: 100px;
      height: 100px;
      border: 3px solid brown;
    } 
    
    main {
      padding: 0 1em;
    }
    <div id="sidebar">
      <img id="logo" src="http://picsum.photos/200">
    </div>
    
    <main>
      <p>This is the part for text</p>
    </main>
    Login or Signup to reply.
  2. You need to assign position: relative to the #main-pic element, so its children could use its relative dimensions properly:

    body {
      display: flex;
    }
    
    #main-pic {
      width: 40%;
      height: 700px;
      
      /* added */
      position: relative;
    }
    
    #main-pic>img {
      width: 100%;
      height: 100%;
    }
    
    #logo-holder {
      width: 100%;
      height: 100px;
      background-color: brown;
      position: absolute;
      top: 50%;
    }
    <div id="main-pic">
      <img src="https://picsum.photos/id/42/400/800" alt="My Flower">
      <div id="logo-holder"></div>
    </div>
    
    <div id="main-text">
      <p>This is the part for text</p>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search