S1r-Lanzelot
S1r-Lanzelot

Reputation: 2266

SVG to center in parent div whose height is set by font

I am trying to center the svg in the parent div while not expanding its overall height beyond the text within this parent. I can get it to center but for some reason the svg child div seemingly takes on an arbitrary height. Any ideas?

#child{
  background:yellow;
}

#child svg{
  width:24px;
  height:100%;
  display:inline-block;
}

#parent{
  display:flex;
  background:silver;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>title</title>
  </head>
  <body>
  <div id="parent">
  <h1>
  hi
  </h1>
   <div id="child">
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
    <path d="M0 0h24v24H0z" fill="none"/>
    <path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"/>
</svg>
  </div>
  </div>
 
  </body>
</html>

I have tried specifying the width and height to 100% of the svg but that will cause the image to be very large. I have also tried setting both the width and height of the svg to 24px but it no longer centers. I have also tried line-height but with no avail. I do not want to give a height to the parent.

Upvotes: 0

Views: 118

Answers (1)

ccprog
ccprog

Reputation: 21821

You can either add the <svg> just inside the <h1> tag, or add a second <h1> containing the SVG on its own (inline-block is the default, no need to state it). The only difference is, in the first case line wrapping is governed by standard text white-space/linebreak behaviour, in the second case by the flex rules of the parent div.

#child{
  background:yellow;
}

#child svg{
  width:24px;
  height:100%;
}

#parent{
  display:flex;
  background:silver;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>title</title>
  </head>
  <body>
  <div id="parent">
  <h1>
  hi
  </h1>
   <h1 id="child">
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
    <path d="M0 0h24v24H0z" fill="none"/>
    <path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"/>
</svg>
  </h1>
  </div>
 
  </body>
</html>

Upvotes: 2

Related Questions