Html div margin javascript

Changing margin of a div with javascript

I’m making a webpage that contains a picture gallery. I’ve written a javascript function to display a larger version of an image when you click on the miniature. What the function does is that it changes the search path of an img tag within a div that is hidden. It then changes the top and left values of the div to position the div in the center of the screen and then it’s supposed to adjust the top and left margin of the div depending on the image size to place its middle in the center of the screen. This is where it fails. Or really, it works, but not when it’s supposed to. If I open an image for the first time it has the wrong offset from the center (the negative margins for top and left are wrong). If I open it again however, it works! I get the same error if I open an image with a different width and height. This is the code used to set the margins:

 imagebox.style.marginLeft=(image.width/-2)+'px'; imagebox.style.marginTop=(image.height/-2)+'px'; 

This works just fine in google chrome and and in safari, but in other browsers it doesn’t always use this code and sometimes it gives it a double call. And in the end I of course set the div visibility to visible.

Читайте также:  Игровой кнопочный телефон java

Open an image the first time to get the error. Then zoom the page in and out (Ctrl+mousewheel works for this, or Ctrl++ and Ctrl+-). If the margins «magically» fix themselves, then it’s a common redraw error. If not, then we can look further into code errors.

Источник

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.

Источник

Свойство 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 margin Property

The margin property sets or returns the margins of an element.

This property can take from one to four values:

  • One value, like: div — all four margins will be 50px
  • Two values, like: div — the top and bottom margins will be 50px, left and right margins will be 10px
  • Three values, like: div — the top margin will be 50px, left and right margin will be 10px, bottom margin will be 20px
  • Four values, like: div — the top margin will be 50px, right margin will be 10px, bottom margin will be 20px, left margin will be 30px

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 margin property:

Property Values

Value Description
% Defines the margins in % of the width of the parent element
length Defines the margins in length units
auto The browser sets the margins (all four margins will be equal)
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 all four margins of a element to «25px»:

Example

Return the margins of a element:

Example

Difference between the margin property and the padding property:

function changeMargin() <
document.getElementById(«myDiv»).style.margin = «100px»;
>

function changePadding() document.getElementById(«myDiv2»).style.padding = «100px»;
>

Источник

Оцените статью