Home > other >  Setting the width of a deeply nested html element
Setting the width of a deeply nested html element

Time:07-04

If I have very nested HTML code that looks something like this:

<body style="margin: 8px;">
  <div>
    <div>
      <div>
        Some content...
      </div>
    </div>
  </div>
</body>

...and I want the innermost div to span the entire width of the screen on smaller devices, up to a maximum width, but not ignore the margin of the body, how can I best do that? If I set the width of the innermost div to 100%, it has no effect because the other divs are only as wide as their content, but if I set the innermost divs width to 100vw, then it ignores the margin of the body. Is there a simpler way than setting the width of all divs so that I can use %?

CodePudding user response:

You can try the following: -

<body style="margin: 8px;">
  <div style="width:100%">
    <div style="width:100%">
      <div style="width:100%">
        Some content...
      </div>
    </div>
  </div>
</body>

CodePudding user response:

div elements are block-level elements, that means that they will be the full width of their parent container by default. Unless there are styles in the parent div elements that override this behavior, your innermost div will be full width while respecting any margin values of its ancestors.

If you have styles in the parent elements that override the block behavior, then you'll want to undo those changes for mobile sizes. This can be achieved using a media-query in CSS.

Here is a contrived example.

body {
  margin: 8px;
  border: 1px solid black;
}

.less-width {
  width: 50%;
  background-color: lightgrey;
}

@media (max-width: 450px) {
  .less-width {
    width: auto;
  }
}
<body>
  <div >
    <div>
      <div>
        <div>SomeContent</div>
      </div>
    </div>
  </div>
</body>

How it works

The @media property of CSS takes in arguments where you can define the condition in which the nested styles will be applied. A common pattern is to check for screen width, and to write styles for mobile views with a max-width argument passed.

Inside the media query, I created a style rule that targets the ancestor of the content and sets its width back to the default behavior with auto.

If your actual code has all div elements as ancestors all the way up to the body, then you will want to look for style rules that override this behavior (such as flex, width, or display), and undo those styles in a media query.

If there are other elements as ancestors to your content, check that these elements are block-level elements. For example, a span is not a block-level element, so it will not take up the full width by default.

  • Related