Robert Li Robert Li - 5 months ago 9
CSS Question

How to set a child's element 50px narrower to its parent element in css?

Most tutorials just tell me something like:

width: 100%;


or something like:

width: 200px;


However, I just want to set the width of child element 50px smaller than that of the parent element.

Answer

There are different ways to accomplish this. I think these are the two most obvious ones:

  1. You could specify a margin

This makes it harder to position an extra element next to it, since the remaining space is still claimed by the margin on the child element.

.outer {
  border: 1px solid blue;
}

.inner {
  border: 1px solid red;
  margin: 0 50px 0 0;
}
<div class="outer"><div class="inner">Demo

  1. Or you could use calc

This method is more convenient if you need to add an extra element next to it. You could use float: left or display: inline-block to help the next element to appear right of the child.

.outer {
  border: 1px solid blue;
}

.inner {
  border: 1px solid red;
  width: calc(100% - 50px);
}
<div class="outer"><div class="inner">Demo

  1. Use Position: absolute

This can be very useful and powerful, but it has some side effects too. As you can see in the snippet, the parent element collapses in height and is unaffected by the side of the child. This might not be a problem, and can even be useful as long as you know what you're doing. The second child element could also be positioned in this way, by specifying a width (50px) and just the right position (0).

.outer {
  border: 1px solid blue;
  position: relative;
}

.inner {
  border: 1px solid red;
  position: absolute;
  left: 0;
  right: 50px;
}
<div class="outer"><div class="inner">Demo

Comments