6
votes

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.

5
is the div you are trying to assign a style of max-width empty??,max width, would not be visible if the div is empty.tomexsans
I think your content div is empty.RAN
The div is not empty lol, just contains text. See @jayx 's answer cause his is exactly what I needed.Emily Ryder
Other question with some additional info.PetaspeedBeaver

5 Answers

14
votes

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.

3
votes

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;
}
0
votes

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.

0
votes

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;
}
0
votes

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.