Home > Software engineering >  How to keep the image in place when screen size changes? HMTL/CSS
How to keep the image in place when screen size changes? HMTL/CSS

Time:11-24

I'm trying to make a html header with a title and an image on the right side of the title. But when the screen size alters the image moves over sliding over the title. How do a make it stay in its place? I've tried all I can think of with no luck. Best that I have come up with is when the image is under the title. Then it keeps its place. But I'd rather have it on the side.

Here is my code:

<body>
  <header>
    <img style="position=absolute; right: 800px; top: 20px;" src="assets/images/something" with="60" height="100">
  </header>
some code ....
</body>

and the header part:

header {
   padding: 25px 20px 40px 20px;
   margin: 0;
   position: fixed;
   top: 0;
   left: 0;
   right: 0;
   width: 100%;
   text-align: center;
   background: xxxx;
   boxäshadow: xxx;
   z-index: 99;
   -webkit-font-smoothing: antialiased;
   min-height: 76px;
}

CodePudding user response:

You have a property set for your header text-align: center; it aligns your image to center because it's inline element. You have many options to change it:

  • set text-align: right;
  • put your image into a block element like <div>
  • change property of your image to block or flex... ex: display: block; and change position of your div with float:right
  • other stuff

Look examples W3school

Use Sandbox like Codepen

CodePudding user response:

You said that the image is sliding over the title.., which title do you mean, there is none? I added a <h1> to your header where you can write your title in.

header {
  margin: 0;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: gray;
  -webkit-font-smoothing: antialiased;
  min-height: 76px;
}
<body>
  <header>
    <h1 style="float: left;">Title Text</h1>
    <img style="float: left;" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Stack_Overflow_icon.svg/768px-Stack_Overflow_icon.svg.png" with="60" height="100">
  </header>
  some code ....
</body>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

If you want the layout of the following content to be aligned right under the header, you can add for example a <div> with the same hight as the header, so the whole WebSite is shiftet down:

<body>
  <header>
   <h1 style="float: left;">Title Text</h1>
   <img style="float: left;" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Stack_Overflow_icon.svg/768px-Stack_Overflow_icon.svg.png" with="60" height="100">
  </header>
  <div style="height: 76px;"></div>
  some code ....
</body>
  • Related