margin-top

Body tag style by using CSS in a webpage

We can use body tag to define style of our page by using different styles like background color , background image with fixed and repeat styles. This style saves our effort and code and we can manage easily the style of our website by editing the external cascade style sheet.

We will discuss various style properties and how they are to be used in external style sheet file.

Let us start with top margin of the page.

Now the page will be flushed with the top bar of the browser window as we have given top margin as 0

Background color of the page

We can specify the background color of the page and this color will be used throughout the page. So the unused space at left and right bottom of the page will be filled with background color specified in style sheet.

Using background image.

We can use any background image for the page by using style sheet for the body tag. We need to tell before that we are going to use image by saying url.

As you have seen in above demo page the background image is repeated many times. If we want to display the background image once only then we can add this code for not repeating the image at background

As we have seen above the background image is positioned at left top location of the page. We can position it based on our requirement. This line of code will position it at left side centre of the page

So we can place the background image at different places by using style of body tag. You have seen how to use no-repeat and display the iamge once only, now we will try not to fix the background image in all the direction and allow it to repeat in either x ( horizontal ) or y ( vertical ) direction. Here is the code

Fixing background image without scrolling along with the page

In the above example you can easily change the direction to vertical by changing the code to repeat-y . Now we will learn how to fix the background image in one location. Here as we scroll up or down the background image will be fixed at the centre. There will be no scrolling of the image. This technique is used for watermarked logo you want to be fixed through out the page at the background. Let us try this code here.

body < background-color: #cfcfcf; margin-top: 0.0em; background-image:url(plus_logo.jpg); background-repeat: no-repeat; background-position: center center; background-attachment: fixed;>

plus2net.com

Читайте также:  Форма обратной связи

Источник

margin-top

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

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

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

Синтаксис

margin-top: значение | auto | inherit

Значения

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

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

HTML5 CSS2.1 IE Cr Op Sa Fx

        
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

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

Применение свойства margin-top

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

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

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

Браузеры

Браузер Internet Explorer 6 в некоторых случаях некорректно вычисляет значение отступа, заданное в процентах.

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

Источник

margin-top

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

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

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

Синтаксис

margin-top: значение | auto | inherit

Значения

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

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

HTML5 CSS2.1 IE Cr Op Sa Fx

        
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

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

Читайте также:  Comparator java по убыванию

Применение свойства margin-top

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

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

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

Браузеры

Браузер Internet Explorer 6 в некоторых случаях некорректно вычисляет значение отступа, заданное в процентах.

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

Источник

margin-top

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

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

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

Краткая информация

Синтаксис

Синтаксис

Описание Пример
Указывает тип значения.
A && B Значения должны выводиться в указанном порядке. &&
A | B Указывает, что надо выбрать только одно значение из предложенных (A или B). normal | small-caps
A || B Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. width || count
[ ] Группирует значения. [ crop || cross ]
* Повторять ноль или больше раз. [,]*
+ Повторять один или больше раз. +
? Указанный тип, слово или группа не является обязательным. inset?
Повторять не менее A, но не более B раз.
# Повторять один или больше раз через запятую. #

Значения

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

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

Песочница

Винни-Пух был всегда не прочь немного подкрепиться, в особенности часов в одиннадцать утра, потому что в это время завтрак уже давно окончился, а обед ещё и не думал начинаться. И, конечно, он страшно обрадовался, увидев, что Кролик достаёт чашки и тарелки.

Пример

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

Применение свойства margin-top

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

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

Объект.style.marginTop

Примечание

Браузер Internet Explorer до версии 7 в некоторых случаях некорректно вычисляет значение отступа, заданное в процентах.

Спецификация

Спецификация Статус
CSS Basic Box Model Рабочий проект
CSS Transitions Рабочий проект
CSS Level 2 (Revision 1) Рекомендация
CSS Level 1 Рекомендация

Спецификация

Каждая спецификация проходит несколько стадий одобрения.

  • Recommendation ( Рекомендация ) — спецификация одобрена W3C и рекомендована как стандарт.
  • Candidate Recommendation ( Возможная рекомендация ) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
  • Proposed Recommendation ( Предлагаемая рекомендация ) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
  • Working Draft ( Рабочий проект ) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
  • Editor’s draft ( Редакторский черновик ) — черновая версия стандарта после внесения правок редакторами проекта.
  • Draft ( Черновик спецификации ) — первая черновая версия стандарта.

Браузеры

В таблице браузеров применяются следующие обозначения.

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

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

См. также

Справочник CSS

  • !important
  • ::after
  • ::backdrop
  • ::before
  • ::first-letter
  • ::first-line
  • ::placeholder
  • ::selection
  • :active
  • :blank
  • :checked
  • :default
  • :disabled
  • :empty
  • :enabled
  • :first-child
  • :first-of-type
  • :focus
  • :focus-within
  • :fullscreen
  • :hover
  • :in-range
  • :indeterminate
  • :invalid
  • :lang
  • :last-child
  • :last-of-type
  • :link
  • :not
  • :nth-child
  • :nth-last-child
  • :nth-last-of-type
  • :nth-of-type
  • :only-child
  • :only-of-type
  • :optional
  • :out-of-range
  • :placeholder-shown
  • :read-only
  • :read-write
  • :required
  • :root
  • :target
  • :valid
  • :visited
  • @charset
  • @document
  • @font-face
  • @import
  • @keyframes
  • @media
  • @page
  • @supports
  • @viewport
  • align-content
  • align-items
  • align-self
  • all
  • animation
  • animation-delay
  • animation-direction
  • animation-duration
  • animation-fill-mode
  • animation-iteration-count
  • animation-name
  • animation-play-state
  • animation-timing-function
  • aspect-ratio
  • backdrop-filter
  • backface-visibility
  • background
  • background-attachment
  • background-blend-mode
  • background-clip
  • background-color
  • background-image
  • background-origin
  • background-position
  • background-position-x
  • background-position-y
  • background-repeat
  • background-size
  • block-size
  • border
  • border-bottom
  • border-bottom-color
  • border-bottom-left-radius
  • border-bottom-right-radius
  • border-bottom-style
  • border-bottom-width
  • border-collapse
  • border-color
  • border-image
  • border-left
  • border-left-color
  • border-left-style
  • border-left-width
  • border-radius
  • border-right
  • border-right-color
  • border-right-style
  • border-right-width
  • border-spacing
  • border-style
  • border-top
  • border-top-color
  • border-top-left-radius
  • border-top-right-radius
  • border-top-style
  • border-top-width
  • border-width
  • bottom
  • box-decoration-break
  • box-shadow
  • box-sizing
  • caption-side
  • caret-color
  • clear
  • clip
  • color
  • column-count
  • column-fill
  • column-gap
  • column-rule
  • column-rule-color
  • column-rule-style
  • column-rule-width
  • column-span
  • column-width
  • columns
  • content
  • counter-increment
  • counter-reset
  • cursor
  • direction
  • display
  • empty-cells
  • filter
  • flex
  • flex-basis
  • flex-direction
  • flex-flow
  • flex-grow
  • flex-shrink
  • flex-wrap
  • float
  • font
  • font-family
  • font-kerning
  • font-size
  • font-stretch
  • font-style
  • font-variant
  • font-weight
  • height
  • hyphens
  • image-rendering
  • justify-content
  • left
  • letter-spacing
  • line-clamp
  • line-height
  • list-style
  • list-style-image
  • list-style-position
  • list-style-type
  • margin
  • margin-bottom
  • margin-left
  • margin-right
  • margin-top
  • marks
  • max-height
  • max-width
  • min-height
  • min-width
  • mix-blend-mode
  • object-fit
  • opacity
  • order
  • orphans
  • outline
  • outline-color
  • outline-offset
  • outline-style
  • outline-width
  • overflow
  • overflow-x
  • overflow-y
  • padding
  • padding-block
  • padding-block-end
  • padding-block-start
  • padding-bottom
  • padding-inline
  • padding-inline-end
  • padding-inline-start
  • padding-left
  • padding-right
  • padding-top
  • page-break-after
  • page-break-before
  • page-break-inside
  • perspective
  • perspective-origin
  • place-content
  • pointer-events
  • position
  • quotes
  • resize
  • right
  • scroll-behavior
  • tab-size
  • table-layout
  • text-align
  • text-align-last
  • text-decoration
  • text-decoration-color
  • text-decoration-line
  • text-decoration-skip-ink
  • text-decoration-style
  • text-emphasis
  • text-emphasis-color
  • text-emphasis-position
  • text-emphasis-style
  • text-fill-color
  • text-indent
  • text-orientation
  • text-overflow
  • text-shadow
  • text-stroke
  • text-stroke-color
  • text-stroke-width
  • text-transform
  • top
  • transform
  • transform-origin
  • transform-style
  • transition
  • transition-delay
  • transition-duration
  • transition-property
  • transition-timing-function
  • unicode-bidi
  • user-select
  • vertical-align
  • visibility
  • white-space
  • widows
  • width
  • word-break
  • word-spacing
  • word-wrap
  • writing-mode
  • z-index
  • zoom

Источник

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