Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS relative position with right side relative to viewport

Tags:

html

css

I have several divs, each a child of the previous. They're all positioned relative, so that I can offset the children relative to the parents. I want to have the right sides line up, but I can't figure out how. Doing width: 100% obviously doesn't work because it ignores that the divs are not at left: 0.

As you can see, the divs escape the viewport:

div {
  position: relative;
  width: 100%;
  height: 250px;
  left: 50px;
  top: 50px;
}

#div1 {
  background-color: #4286f4;
}

#div2 {
  background-color: #3267bc;
}

#div3 {
  background-color: #244a87;
}
<div id="div1">
  <div id="div2">
    <div id="div3">
      
    </div>
  </div>
</div>

Or if you prefer: JSFiddle

How can I position the right side of each div at some specific distance from the right side of the screen with only CSS?

This is the expected output (the black rectangle around the outside represents the edges of the screen):

enter image description here

like image 816
Clonkex Avatar asked Nov 24 '25 21:11

Clonkex


1 Answers

You might consider using margin-left instead of left.

With the CSS box model default, "width and height properties include the content, but does not include the padding, border, or margin," (box-sizing).

Also, block-level elements take up "the full width available", so width:100% isn't necessary (Block-level elements).

body {
  margin: 20px 60px 20px 20px;
}

div {
  position: relative;
}

div div {
  height: 80px;
  margin-left: 40px;
  top: 40px;
}

#div1 {
  background-color: #4286f4;
}

#div2 {
  background-color: #3267bc;
}

#div3 {
  background-color: #244a87;
}
<div id="div1">
  <div id="div2">
    <div id="div3"></div>
  </div>
</div>
like image 126
showdev Avatar answered Nov 27 '25 13:11

showdev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!