educative.io

Exercise to use margins to center an HTML element not displayed correctly

I thought I had the CSS specified correctly, but it did not show that way in the Output box. In the developer console in chrome I could see only the user agent stylesheet was applied to the h1 element, the div looked okay. So, I pushed the test button and it passed, so at least that worked. Thank you.
I’m not sure how these categories / selections are supposed to be, almost made it so I could not submit this question.

Hi @Carol_Enderlin !!
It seems like you encountered some confusion with how the code was displayed in the output box and the application of CSS styles. The following code should center the <h1> element within the <div>. Here’s a breakdown of what your code should do:

<html>
 <head>
   <title>Centering elements using margins</title>
   <style>
     div {
       border: 5px solid blue;
     }

     h1 {
       border: 5px solid black;
       width: 50%;
       margin-left: 25%;
       margin-right: 25%;
     }
   </style>
 </head>
 <body>
   <div>
     <h1>This element should be centered.</h1>
   </div>
 </body>
</html>

This code should correctly center the <h1> element within the <div> using margins. The width: 50%; for the <h1> element ensures it takes up half the width of its parent <div>. The margin-left: 25%; and margin-right: 25%; create an equal left and right margin of 25% of the parent’s width, effectively centering the <h1> element.

If you encountered a display issue in the output box but the test passed, it’s possible that there might have been some interference or misunderstanding due to the development environment you were using.

If you have any further questions or issues, feel free to provide more details, and I’ll be glad to assist you further.
Happy Learning :blush: