Search code examples
htmlcsshtml-tablemargin

Zero-out margin of single elements


Is there any way of zeroing-out the margin of single elements? In the code snippet I've zeroed-out the margin by setting the html and body margin to 0. But actually I would like to zero-out the margin of the table only, so that its inner content and the rest of the html body content keeps the 'standard' margin.

Have a look to the screenshots I've added.

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <style>
      html, body {
	margin: 0;
	padding: 0;
}
table {
	border-collapse: collapse;
	border-spacing: 0;
  background-color: #000;
  width: 100%;
}
</style>
    <title>Zero-out margin of single elements</title>
  </head>

  <body>
  <p>This text should've its standard margin</p>
    <table>
    <td>
    <p style="color: white">This text should've its standard margin. Only the table should extend the browser width.</p>
    </td>     
    </table>
    <hr>
    <p>This hr should've its standard margin too</p>
  </body>

</html>

Have a look at this to better understand what I mean: https://meyerweb.com/eric/tools/css/reset/

Content extending/ reaching full browser width: https://jsfiddle.net/48qeuanf/1/

Content not extending/reaching full browser width (standard margin): https://jsfiddle.net/48qeuanf/2/

Browser with default margin:

Html extending default margin

Browser with default margin (Code)]:

Html extending default margin (Code):


Solution

  • Change your CSS to this:

         body
    {
      margin:0
    }
    body > *
    {
      margin:3px;
      background-color: #FF0000;
    }
    table {
        border-collapse: collapse;
        border-spacing: 0;
      background-color: black;
      width: 100%;
      margin : initial
      }
      td > p
      {
        margin:2px;
      }
    

    The initial keyword is used to set a CSS property to its default value. The element > * selector selects all the child elements of that element

    Check the fiddle