Home >Web Front-end >CSS Tutorial >How Can I Create a Div with 100% Width and Maintain Margins?

How Can I Create a Div with 100% Width and Maintain Margins?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 11:12:14837browse

How Can I Create a Div with 100% Width and Maintain Margins?

Display a Div with 100% Width and Margins

Creating a div with 100% width while maintaining margins can be a challenge. However, there are several approaches to achieve this:

float and calc() CSS Function:

The float property can position the div horizontally without affecting the flow of other elements. The calc() function can be used to calculate the desired width for the div with margins.

#page {
  background: red;
  float: left;
  width: 100%;
  height: 300px;
}

#margin {
  background: green;
  float: left;
  width: calc(100% - 10px);
  height: 300px;
  margin: 10px;
}

padding and box-sizing: border-box

Padding and box-sizing can also be used to create the desired effect:

#page {
    background: red;
    width: 100%;
    height: 300px;
    padding: 10px;
}

#margin {
    box-sizing: border-box;
    background: green;
    width: 100%;
    height: 300px;
}

With box-sizing set to border-box, the padding is included in the width calculation. This ensures that the margins are applied outside the padded area.

The above is the detailed content of How Can I Create a Div with 100% Width and Maintain Margins?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn