简体   繁体   中英

CSS: fixed positioning, right: 0px but won't obey max-width

I cannot get positioning, max-width, and 'right: 0px' to work together in harmony! I'm creating a div that is fixed on my site in the upper right corner. The content of the page has a max-width of 1000px, however the label only obeys my rule of 'right: 0px' and sticks to the right, disobeying once max-width has been reached. It should also be noted that by default, the div is in the upper left and obeys the max-width (if I type 'left: 0px;' though, it does not obey the rule and it sticks to the left).

CSS:

#content {
margin: 0 auto;
max-width: 1000px; }

#div {
width: 150px;
position: fixed;
right: 0px; } 

Here are some alternatives that I've already tried:

  • width: 100% (with text-align: right) <--- not quite right, and I don't like the 100% width as opposed to 150px
  • adding code to position the div "manually" in the html (not CSS)
  • I've discovered that float and text-align don't affect to fixed positioning

Help is greatly appreciated! Thank you.

If I understand correctly, this is what you're after .

You need to add a container with an absolute position to get the content over to the right and then use a fixed position container to keep it top right where you need it.

Alternative if you don't want to add additional absolute container

#div {
  width: 150px;
  position: fixed;
  right: calc(50% - 500px); /* will move the div as far as 50% of viewport
  then move it back to 500px (that is half of max-width) */
}

/* if needed, you can add media query */
@media (max-width: 1000px) {
  right: 0;
}

I got it working with no problem in a jsfiddle . You may want to look around at the CSS that is affecting the area. You may have an issue if #content is not a block level element (no width will be applied and such. More code from you would be greatly helpful so we know exactly what is going on and can help you out more.

I think you need this one:

#content {
  margin: 0 auto;
  max-width: 1000px; 
  height:20px;
  background:yellow;
  position: relative;
}
#div {
  width: 150px;
  position: absolute;
  right: 0px;
}

position:fixed is not relative to any container. It is relative to the html element of the DOM. That is the reason you're seeing it at extreme right whatever you do to the #content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM