Margin Left

How to margin the body of the page (html)?

is causing your problems. Try nulling its margin too see. And check that collapsing margins link which Alex provided as a comment to his answer.

9 Answers 9

Once you study a bit about css, you can change it to:

@Buffon: Then it’s causing another element. I guess that you have h1 or any other heading as a first element. So null the margins of that element too or provide your code.

the code is : .header < width: 100%; background-color: #3B5998; height: 35px; margin-top:0; >.style1 < margin-right: 38px; >.style2

.

@Nyerguds could you please link a page that says that? As far as I know you shouldn’t define units for zero.

Huh, really? Odd. Seems logical there would always need to be a unit. So, zero is a special case, then?

Html for content, CSS for style

Yeah a CSS primer will not hurt here so you can do two things: 1 — within the tags of your html you can open a style tag like this:

  

2- the above though will only work on the page you have this code embeded, so if if you wanted to reuse this in 10 files, then you will have to copy it over on all 10 files, and if you wanted to make a change let’s say have a margin of 5px instead, you would have to open all those files and make the edit. That’s why using an external style sheet is a golden rule in front end coding. So save the body declaration in a separate file named style.css for example and from your add this to your html instead:

Now you can put this in the of all pages that will benefit from these styles and whenever needed to change them you will only need to do so in one place. Hope it helps. Cheers

Источник

margin

Устанавливает величину отступа от каждого края элемента. Отступом является пространство от границы текущего элемента до внутренней границы его родительского элемента (рис. 1).

Отступ от левого края элемента

Рис. 1. Отступ от левого края элемента

Если у элемента нет родителя, отступом будет расстояние от края элемента до края окна браузера с учетом того, что у самого окна по умолчанию тоже установлены отступы. Чтобы от них избавиться, следует устанавливать значение margin для селектора равное нулю.

Свойство margin позволяет задать величину отступа сразу для всех сторон элемента или определить ее только для указанных сторон.

Синтаксис

margin: [значение | проценты | auto] | inherit

Значения

Разрешается использовать одно, два, три или четыре значения, разделяя их между собой пробелом. Эффект зависит от количества значений и приведен в табл. 1.

Табл. 1. Зависимость от числа значений

Число значений Результат
1 Отступы будут установлены одновременно от каждого края элемента.
2 Первое значение устанавливает отступ от верхнего и нижнего края, второе — от левого и правого.
3 Первое значение задает отступ от верхнего края, второе — одновременно от левого и правого края, а третье — от нижнего края.
4 Поочередно устанавливается отступ от верхнего, правого, нижнего и левого края.

Величину отступов можно указывать в пикселах (px), процентах (%) или других допустимых для CSS единицах. Значение может быть как положительным, так и отрицательным числом.

auto Указывает, что размер отступов будет автоматически рассчитан браузером. inherit Наследует значение родителя.

HTML5 CSS2.1 IE Cr Op Sa Fx

Результат данного примера показан на рис. 2.

Рис. 2

Рис. 2. Применение свойства margin

Объектная модель

[window.]document.getElementById(» elementID «).style.margin

Браузеры

Internet Explorer 6 в режиме совместимости (quirk mode) не поддерживает выравнивание блока по центру с помощью правила margin: 0 auto . Также в этом браузере наблюдается ошибка с удвоением значения левого или правого отступа для плавающих элементов, вложенных в родительские элементы. Удваивается тот отступ, который прилегает к стороне родителя. Проблема обычно решается добавлением display: inline для плавающего элемента.

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .

Примечание

У блочных элементов расположенных рядом друг с другом по вертикали наблюдается эффект схлопывания, когда отступы не суммируются, а объединяются между собой. Само схлопывание действует на два и более блока (один может быть вложен внутрь другого) с отступами сверху или снизу, при этом примыкающие отступы комбинируются в один. Для отступов слева и справа схлопывание никогда не применяется.

Схлопывание не срабатывает:

  • для элементов, у которых на стороне схлопывания задано свойство padding .
  • для элементов, у которых на стороне схлопывания задана граница;
  • на элементах с абсолютным позиционированием, т.е. таких, у которых position установлено как absolute ;
  • на плавающих элементах (для них свойство float задано как left или right );
  • для строчных элементов;
  • для .

Источник

color body set to auto change margin

Here’s my style sheet. I’m trying to get the margin around my body to have a different color from the body itself. Here’s my beginning code. Is a reset section really necessary? Can someone tell me what I’m doing wrong.

3 Answers 3

What you’re looking for is a border. If you want to make the margin around your body red, simply use this:

You may want to try adding padding-top: 20px; to the html instead of margin-top: 20px; with the body:

I believe you also want to change color: #d9a552; to

The html element is not really meant to be styled. If you want to design your webpage, you should use div s instead of doing it the easy way and applying your styles to the html element.

Ultimately, Joeytje50 is correct — a wrapper div that was 100% the size of the body would be more ideal, but you will see some people make use of the html element depending upon needs.

Here’s what I got to work: The problem with that is that if I expand the window the white part returns.

Here’s my solution: I added section tag immediately following the body tag. I gave it a class id of ‘mainBody’. Then I adjusted the code as follows:

I know I can’t give myself credit, but I thought I would share my solution for someone else to use. I will give both you guys credit for steering me in the right direction. Thank you.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

CSS Margin Color

CSS Margin Color

The following article provides an outline on CSS Margin Color. The margin property in HTML gives space around the outermost element’s content of the box-like structure. Margin is creating space beyond the box model elements. So, we cannot apply color to the margin. If our requirement still applies color around the elements, you can use padding instead of a margin.

Web development, programming languages, Software testing & others

The padding property in html gives space around the innermost element’s content of the box-like structure. The space around the padding and margin is called a border.

The difference between the padding, margin, and border you can observe below:

css margin color

  • As we know, common styles in all the pages, we always preferred CSS over HTML.
  • So, in this tutorial, all common properties are implemented in CSS only.
  • As we discussed above, it is not possible to apply different colors. Still, you can vary the margin from the box model by setting the background color of the html page to different color and the margin color by default to white color.

Syntax

Margin can be applied to the sides of the top, right, bottom, and left.

Explanation: If we apply a margin with four values, the first value is for the top, the second value is for the right, the third value is for the bottom, and the fourth value is for the left applied, respectively.

Explanation: If we apply a margin with 3 values, the first value is for the top, the second value is for left and right, and the third value is for the bottom applied, respectively.

Explanation: If we apply a margin with 2 values, then the first value is for the top and bottom, and the second is for the left and right, respectively.

Explanation:

  • If we apply margin with only single values, we use it equally for all four sides.
  • If we want to apply only margin side margin, then CSS provides predefined properties.
  • margin-left: 10px: apply margin 10px to left side.

margin -right: 10px: apply margin 10px to right side.

margin -top: 10px: apply margin 10px to top side.

margin -bottom: 10px: apply margin 10px bottom side.

Examples of CSS Margin Color

Given below are the examples of CSS Margin Color:

Example #1: Applying margin from the left side

       

Without Margin

Just, varying margin from box model with defalt white color. We can't apply special color to margin. If we want to apply colors around the text we can use border or padding with different colors.

With Margin

Just, varying margin from box model with defalt white color. We can't apply special color to margin. If we want to apply colors around the text we can use border or padding with different colors.

applying margin from left side

Explanation:

Example #2: Applying margin from the right side

       

Without Margin

Just, varying margin from box model with defalt white color. We can't apply special color to margin. If we want to apply colors around the text we can use border or padding with different colors.

With Margin

Just, varying margin from box model with defalt white color. We can't apply special color to margin. If we want to apply colors around the text we can use border or padding with different colors.

applying margin from right side

Explanation:

Example #3: Applying margin from the top side

      

Without Margin

Just, varying margin from box model with defalt white color. We can't apply special color to margin. If we want to apply colors around the text we can use border or padding with different colors.

With Margin

Just, varying margin from box model with defalt white color. We can't apply special color to margin. If we want to apply colors around the text we can use border or padding with different colors.

css margin color 4

Explanation:

Example #4: Applying margin from the bottom side

      

With Margin

Just, varying margin from box model with defalt white color. We can't apply special color to margin. If we want to apply colors around the text we can use border or padding with different colors.

Without Margin

Just, varying margin from box model with defalt white color. We can't apply special color to margin. If we want to apply colors around the text we can use border or padding with different colors.

css margin color 5JPG

Explanation:

Conclusion

We can’t apply different colors to the margin because it’s beyond its elements box. We just varied the margin from elements by making the background into different colors and the margin to white color.

We hope that this EDUCBA information on “CSS Margin Color” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

38+ Hours of HD Videos
9 Courses
5 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

149+ Hours of HD Videos
28 Courses
5 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

253+ Hours of HD Videos
51 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

CSS Course Bundle — 19 Courses in 1 | 3 Mock Tests
82+ Hours of HD Videos
19 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

Источник

Читайте также:  Что можно создавать в php
Оцените статью