Search code examples
htmlcssthymeleaf

Horizontally center an image with Thymeleaf


I have this css:

/* Global CSS styles */
body {
    background-color: #364f6b;
    margin: 0;
    padding: 0;
}

/* Styling the logo */
.logo {
    width: 400px;
    height: auto;
    justify-content: center; /* Horizontally center the content */
}

and this template:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    
    <!-- Menu -->
    <link id="themeLink" th:href="@{/css/mystic-planets.css}"  rel="stylesheet" />
    <meta name="format-detection" content="telephone=no">

</head>
<body>
<header>
    <img th:src="@{/images/137364472_padded_logo.png}"  alt="mystic-planets" th:class="logo" />
    <!-- Other header content goes here -->
</header>
</body>
</html>

but the logo appears on the top-left side of the page


Solution

  • justify-content
    justify-item
    

    These properties are sub-parts of CSS flex layout. To use these properties you need to you flex layout first.

      {
         display: flex;
         flex-direction: column;
      }
    

    Do not forget to use the flex-direction row or column. Finally, you can use justify-content and justify-item properties.

    Look at the following example,

    div {
      display: flex;
      justify-content: center;
      justify-items: center;
    }
    

    Hope this is helpful for you.