CSS width minus a value
CSS width minus a certain value
In front-end development, it is often necessary to dynamically adjust the width of an element. Sometimes we need to subtract or add a fixed value to an element’s width. This is where computed properties in CSS come in handy.
CSS Computed Property calc()
CSS provides the calc() function for dynamically calculating values when declaring CSS properties. The calc() function accepts addition, subtraction, multiplication, and division, making it easier to dynamically adjust element widths.
Grammar
width: calc(100% - 20px);
In this example, the element’s width is the percentage of the parent container’s width minus 20px.
Example
HTML Structure:
<div class="container">
<div class="box"></div>
</div>
CSS Style:
.container {
width: 80%;
height: 200px;
background-color: lightblue;
padding: 10px;
}
.box {
width: calc(100% - 20px);
height: 100px;
background-color: lightcoral;
}
In this example, the width of the box element is set to the width of its parent container minus 20px, achieving the effect of dynamically adjusting the width.
Units in CSS
When using CSS computed properties, you need to pay attention to the arithmetic rules between different units.
Percentage and Fixed Value Operations
Percentages and fixed pixel values can be used in calculated properties. For example:
width: calc(50% - 10px);
Conversions Between Different Units
In CSS, different units have specific conversion rules. Generally, browsers convert values from different units to the same unit for calculations. For example:
width: calc(50vh + 50vw);
In this example, the browser converts 50vh (50% of the viewport height) and 50vw (50% of the viewport width) to the same unit for calculations.
Practical Application Scenarios
Responsive Layouts
In responsive layouts, we often need to dynamically adjust element widths based on different screen sizes. Using CSS computed properties allows for more flexible adaptive width adjustments.
@media screen and (max-width: 768px) {
.box {
width: calc(100% - 20px);
}
}
Complex Layout Design
When designing complex layouts, you may need to precisely calculate element widths. The calc() function allows you to more accurately control element widths and achieve more complex layout effects.
.box {
width: calc(33.333% - 10px);
}
Summary
The calc() function in CSS provides a convenient way to dynamically adjust element widths. By flexibly using calculated properties, you can more precisely control element widths and achieve a variety of complex layout effects. In actual development, you can flexibly use the calc() function according to specific needs to achieve a more flexible and elegant page layout design.