Home >Web Front-end >CSS Tutorial >Don&#t use CSS position: absolute to overlay two elements

Don&#t use CSS position: absolute to overlay two elements

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-21 02:04:13137browse

Don

Let's asume you have the following HTML structure to overlay an image with a header:

<div>



<p>You could be tempted to position the header absolute:<br>
</p>

<pre class="brush:php;toolbar:false">.card {
    position: relative;
    width: 300px;
}
.card > * {
    margin: 0;
}
.card header {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: #fff3;
}

...but then you loose layout on the header. Use grid instead:

.card {
    display: grid;
    width: 300px;
}
.card > * {
    grid-area: 1/1;
    margin: 0;
}
.card header {
    background-color: #fff3;
}

Here is a codepen link with the full example.

Happy coding!

The above is the detailed content of Don&#t use CSS position: absolute to overlay two elements. 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