- Style marginTop Property
- Browser Support
- Syntax
- Property Values
- Technical Details
- More Examples
- Example
- Example
- Example
- Related Pages
- COLOR PICKER
- HOW TO
- SHARE
- CERTIFICATES
- Report Error
- Thank You For Helping Us!
- Top Tutorials
- Top References
- Top Examples
- Web Certificates
- Свойство margin
- Объединение отступов
- Отрицательные margin-top/left
- Пример: вынос заголовка
- Пример: вынос разрыва
- Отрицательные margin-right/bottom
- Итого
- Задачи
- Нерабочие margin?
- Расположить текст внутри INPUT
- Подсказка
- Решение
- Style marginTop Property
- Browser Support
- Syntax
- Property Values
- Technical Details
- More Examples
- Example
- Example
- Example
- How to get and set margin in Javascript
- 1. How to set margin in Javascript
- a. Setting all margins using Javascript
- b. Changing top margin only
- c. Changing bottom margin only
- d. Changing left margin only
- e. Changing right margin only
- 2. How to get the value of margin in javascript
- a. getting all margin at once
- b. Getting the value top margin only
- c. Getting the value of bottom margin only
- d. Getting the value of left margin only
- e. Getting the value right margin only
- Related Article
- About
Style marginTop Property
The marginTop property sets or returns the top margin of an element.
Both the margin property and the padding property insert space around an element. However, the difference is that margin inserts the space around the border, while padding inserts the space within the border of an element.
Browser Support
Syntax
Return the marginTop property:
Set the marginTop property:
Property Values
Value | Description |
---|---|
% | Defines the top margin in % of the width of the parent element |
length | Defines the top margin in length units |
auto | The browser sets the top margin |
initial | Sets this property to its default value. Read about initial |
inherit | Inherits this property from its parent element. Read about inherit |
Technical Details
More Examples
Example
Change the top margin of a element back to «normal»:
Example
Return the top margin of a element:
Example
Difference between marginTop and paddingTop:
function changeMargin() <
document.getElementById(«myDiv»).style.marginTop = «100px»;
>
function changePadding() document.getElementById(«myDiv2»).style.paddingTop = «100px»;
>
Related Pages
COLOR PICKER
HOW TO
SHARE
CERTIFICATES
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Web Certificates
W3Schools is optimized for learning, testing, and training. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 1999-2020 by Refsnes Data. All Rights Reserved.
Powered by W3.CSS.
Свойство margin
Свойство margin задаёт отступы вокруг элемента. У него есть несколько особенностей, которые мы здесь рассмотрим.
Объединение отступов
Вертикальные отступы поглощают друг друга, горизонтальные – нет.
Например, вот документ с вертикальными и горизонтальными отступами:
Горизонтальный 20px ← 40px → 20px Отступ
Вертикальный 20px
Расстояние по горизонтали между элементами SPAN равно 40px , так как горизонтальные отступы по 20px сложились.
А вот по вертикали расстояние от SPAN до P равно 20px : из двух вертикальных отступов выбирается больший max(20px, 15px) = 20px и применяется.
Отрицательные margin-top/left
Отрицательные значения margin-top/margin-left смещают элемент со своего обычного места.
В CSS есть другой способ добиться похожего эффекта – а именно, position:relative . Но между ними есть одно принципиальное различие.
При сдвиге через margin соседние элементы занимают освободившееся пространство, в отличие от position: relative , при котором элемент визуально сдвигается, но место, где он был, остаётся «занятым».
То есть, элемент продолжает полноценно участвовать в потоке.
Пример: вынос заголовка
Например, есть документ с информационными блоками:
- водительское удостоверение на право управления транспортным средством соответствующей категории;
- . и так далее.
Использование отрицательного margin-top позволяет вынести заголовки над блоком.
/* вверх чуть больше, чем на высоту строки (1.25em) */ h2
А вот, что бы было при использовании position :
При использовании position , в отличие от margin , на месте заголовков, внутри блоков, осталось пустое пространство.
Пример: вынос разрыва
Организуем информацию чуть по-другому. Пусть после каждого заголовка будет разрыв:
Заголовок
Текст Текст Текст.
Пример документа с такими разрывами:
Для красоты мы хотим, чтобы разрыв HR начинался левее, чем основной текст. Отрицательный margin-left нам поможет:
/*+ no-beautify */ hr.margin < margin-left: -2em; >/* для сравнения */ hr.position
Обратите внимание на разницу между методами сдвига!
- hr.margin сначала сдвинулся, а потом нарисовался до конца блока.
- hr.position сначала нарисовался, а потом сдвинулся – в результате справа осталось пустое пространство.
Уже отсюда видно, что отрицательные margin – исключительно полезное средство позиционирования!
Отрицательные margin-right/bottom
Отрицательные margin-right/bottom ведут себя по-другому, чем margin-left/top . Они не сдвигают элемент, а «укорачивают» его.
То есть, хотя сам размер блока не уменьшается, но следующий элемент будет думать, что он меньше на указанное в margin-right/bottom значение.
Например, в примере ниже вторая строка налезает на первую:
Первый Второй div думает, что высота первого на 0.5em меньше
Это используют, в частности для красивых вносок, с приданием иллюзии глубины.
Итого
- Отрицательные margin-left/top сдвигают элемент влево-вверх. Остальные элементы это учитывают, в отличие от сдвига через position .
- Отрицательные margin-right/bottom заставляют другие элементы думать, что блок меньше по размеру справа-внизу, чем он на самом деле.
Отличная статья на тему отрицательных margin : The Definitive Guide to Using Negative Margins
Задачи
Нерабочие margin?
В примере ниже находится блок .block фиксированной высоты, а в нём – прямоугольник .spacer .
При помощи margin-left: 20% и margin-right: 20% , прямоугольник центрирован в родителе по горизонтали. Это работает.
Далее делается попытка при помощи свойств height: 80% , margin-top: 10% и margin-bottom: 10% расположить прямоугольник в центре по вертикали, чтобы сам элемент занимал 80% высоты родителя, а сверху и снизу был одинаковый отступ.
Однако, как видите, это не получается. Почему? Как поправить?
Ошибка заключается в том, что margin при задании в процентах высчитывается относительно ширины. Так написано в стандарте.
При этом не важно, какой отступ: левый, правый. верхний или нижний. Все они в процентах отсчитываются от ширины. Из-за этого и ошибка.
Ситуацию можно исправить, например, заданием margin-top/margin-bottom в пикселях, если это возможно или, в качестве альтернативы, использовать другие средства, в частности, position или padding-top/padding-bottom на родителе.
Расположить текст внутри INPUT
Создайте с цветной подсказкой внутри (должен правильно выглядеть, не обязан работать):
В дальнейшем мы сможем при помощи JavaScript сделать, чтобы текст при клике пропадал. Получится красивая подсказка.
P.S. Обратите внимание: type=»password» ! То есть, просто value использовать нельзя, будут звёздочки. Кроме того, подсказка, которую вы реализуете, может быть как угодно стилизована.
P.P.S. Вокруг INPUT с подсказкой не должно быть лишних отступов, блоки до и после продолжают идти в обычном потоке.
Подсказка
Надвиньте элемент с текстом на INPUT при помощи отрицательного margin .
Решение
Надвинем текст на INPUT при помощи отрицательного margin-top . Поднять следует на одну строку, т.е. на 1.25em , можно для красоты чуть больше – 1.3em :
Также нам понадобится обнулить «родной» margin у INPUT , чтобы не сбивал вычисления.
Style marginTop Property
The marginTop property sets or returns the top margin of an element.
Both the margin property and the padding property insert space around an element. However, the difference is that margin inserts the space around the border, while padding inserts the space within the border of an element.
Browser Support
Syntax
Return the marginTop property:
Set the marginTop property:
Property Values
Value | Description |
---|---|
% | Defines the top margin in % of the width of the parent element |
length | Defines the top margin in length units |
auto | The browser sets the top margin |
initial | Sets this property to its default value. Read about initial |
inherit | Inherits this property from its parent element. Read about inherit |
Technical Details
More Examples
Example
Change the top margin of a element back to «normal»:
Example
Return the top margin of a element:
Example
Difference between marginTop and paddingTop:
function changeMargin() <
document.getElementById(«myDiv»).style.marginTop = «100px»;
>
function changePadding() document.getElementById(«myDiv2»).style.paddingTop = «100px»;
>
How to get and set margin in Javascript
Margin in javascript is the same margin in html. You can set the amount of margin an element has using Javascript. To be clear, margin is the space between the border and the outside container holding the element.
1. How to set margin in Javascript
You can change the margin an element using the margin property. Lets look at how you can do this.
a. Setting all margins using Javascript
You can change the margin using the margin property «margin» in javascript. You can then use the id of the element to set the new margin:
var box= document.querySelector("#box"); box.addEventListener('click', function()< box.style.margin="50px 100px 50px 100px"; >);
b. Changing top margin only
You are going to use the «marginTop» property to set the top margin only using javascript.
box.addEventListener('click', function()< box.style.marginTop="100px"; >);
c. Changing bottom margin only
You can use the «marginBottom property to change the bottom margin in javascript.
box.addEventListener('click', function()< box.style.marginBottom="50px"; >);
The element now has a margin of 50 pixels.
d. Changing left margin only
The «marginRight» property sets the new left margin to 100px.
box.addEventListener('click', function()< box.style.marginLeft="100px"; >);
e. Changing right margin only
To change the right margin only use the «marginRight» property.
box.addEventListener('click', function()< box.style.marginRight="50px"; >);
2. How to get the value of margin in javascript
Its also possible for you to obtain the values of margin using Javascript.
let’s begin by getting the value of all styles applied to the “box” element. To get these styles you use window.getComputedStyle(box) .
In addition, you can make sure its compatible with older versions of Internet Explorer by add box.CurrentStyle .
var style= window.getComputedStyle(box) || box.currentStyle
You can now use a simple console.log(style.margin) or alert(style.margin) to get the margin values.
a. getting all margin at once
The full code should be as following:
//a. Getting all margins using Javascript box.addEventListener('click', function() var style = box.currentStyle || window.getComputedStyle(box) console.log(style.margin); >);
b. Getting the value top margin only
You can get the top margin value using this code:
// b. Getting top margin only box.addEventListener('click', function() var style = box.currentStyle || window.getComputedStyle(box) console.log(style.marginTop); >);
c. Getting the value of bottom margin only
Use the following code to get the bottom margin:
//c. Getting bottom margin only box.addEventListener('click', function() var style = box.currentStyle || window.getComputedStyle(box) console.log(style.marginBottom); >);
d. Getting the value of left margin only
The code for getting the value of right margin only:
//d. Getting left margin only box.addEventListener('click', function() var style = box.currentStyle || window.getComputedStyle(box) console.log(style.marginLeft); >);
e. Getting the value right margin only
The code for getting the value of right margin only:
//e. Getting right margin only box.addEventListener('click', function() var style = box.currentStyle || window.getComputedStyle(box) console.log(style.marginRight); >);
Related Article
Front End Developer Newsletter
Receive a monthly Frontend Web Development newsletter.
Never any spam, easily unsubscribe any time.
Start understanding the whole web development field now
Stop all the confusion and start understanding how all the pieces of web development fit together.
Never any spam, easily unsubscribe any time.
About
If you are just starting out you can test the waters by attempting the project-based HTML tutorial for beginners that I made just for you.
Okay, you got me there, I made it because it was fun and I enjoy helping you on your learning journey as well.
You can also use the HTML and CSS projects list as a source of projects to build as you learn HTML, CSS and JavaScript.
Copyright © 2018 — 2023 DevPractical. All rights reserved.