-1

I am trying to align the element by using my method, however, I get in trouble with getting the current height of the element by using CSS.
This is the code that works, but there will be some extral part.

section{
  margin-top:calc(50vh);
  margin-bottom:calc(50vh);
}
<section style="background:red;">q<br><br>q</section>

This is what I want to do, but it is not working:

section{
  margin-top:calc(50vh - attr(clientHeight));
  margin-bottom:calc(50vh - attr(clientHeight));
}
<section style="background:red;">q<br><br>q</section>

I want to know how to get the height of the element, and this question is forcus on this point, but not align an element vertically. Furthermore, I want a CSS-only solution.

Han Han
  • 328
  • 12
  • 1
    If you want to vertically center the element, don’t use margins. There are so many other ways to do it without needing to explicitly access the element’s own height. – Terry Mar 14 '23 at 05:47
  • Could you describe what you want the final result to look like because I don't understand the calcs you have given - the margins would together add up to 100vw minus twice the height of the element. Are you trying to vertically center the element in the viewport? – A Haworth Mar 14 '23 at 07:30

1 Answers1

0

I hope this example works for you

body {
    padding: 0px;
    margin: 0px;
}

.wrap {
    display: flex;
    align-items: center;
    justify-content: center;

    height: 100vh;
}
<div class="wrap">
    <section style="background:red;">
        123
        <br><br>
        123
    </section>
</div>
54ka
  • 3,501
  • 2
  • 9
  • 24